473,320 Members | 1,904 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Convert Integer to Binary

114 100+
Is it possible in C?

Is there a certain formula?
Jul 17 '07 #1
25 11687
archonmagnus
113 100+
Sure. The general idea works by using remainders. For example, suppose the input value is 9.

9 / 2^4 = 0 remainder 9
9 / 2^3 = 1 remainder 1
1 / 2^2 = 0 remainder 1
1 / 2^1 = 0 remainder 1
1 / 2^0 = 1 remainder 0

[the general equation is (remainder / 2^i)]

So the returned output would be: "01001" -- which is equivalent to 9

The most straight-forward way (but not most efficient) to do this in code (for 0 <= input < 256) is:
Expand|Select|Wrap|Line Numbers
  1. scanf("%d", input);
  2.  
  3. for (i = 7; i >= 0; i--)
  4. {
  5.     output[7 - i] = input / pow(2.0, i);
  6.     input %= (int)pow(2.0, i);
  7. }
  8.  
  9. for (i = 0; i < 8; i++)
  10.     printf("%d", output[i]);
  11.  
(Disclaimer: I haven't tested this, but the general idea is the same.)
Jul 17 '07 #2
iWillLiveforever
136 100+
It is always possible to convert in any language you just have to do the math.

I’m guessing the integer is in base 10

So say you have the number 23 that you want to convert into binary

23-(2^4)=7
1

7-(2^3) =put in a zero
0

7-(2^2) =3
1

3-(2^1)=1
1

1-(2^0)=0
1

so 23 base 10 = 10111 binary

And can someone check my work to make sure its correct.
Jul 17 '07 #3
linkid
1
Why do i set y=pow(x,1/3), the result always be "1.000000"?

For example

y=pow(8,1/3) ---> y=1.000000
Jul 18 '07 #4
Why do i set y=pow(x,1/3), the result always be "1.000000"?

For example

y=pow(8,1/3) ---> y=1.000000
In C/ C++ the pow function takes two arguments. The first argument is of type float or double or int. The second argument must be of type int.

When you are trying to calculate 8^{1/3} using pow(8,1/3), the second argument is cast into int and as such is rounded to zero, so what you are actually calculating is 8^{0}, which will return 1.

To calculate numbers to non-integer powers you are better off using a Newton Method approach. If you read up on Newton's Method you will find the answer.

Also you shouldn't cross-post, hijack another post. It's rude and against the posting guidelines.
Jul 18 '07 #5
weaknessforcats
9,208 Expert Mod 8TB
Is it possible in C?

Is there a certain formula?
Use the modulus operator.

Take 23 as an example. The binary is 10111.

Do this:

(23/16) % 2 23/16 which is 1 % 2 which is 1
(23/8 ) % 2 23/8 which is 2 % 2 which is 0
(23/4 ) % 2 23/4 which is 5 % 2 which is 1
(23/2 ) % 2 23/2 which is 11 % 2 which is 1
(23/1 ) % 2 23/1 which is 23% 2 which is 1

You can see the bits and I am sure you can write a loop to vary what you divide into 23 by dividing the divisor by 2 on each cycle of the loop.
Jul 18 '07 #6
Firecore
114 100+
I see.
Thank you very much all of you.
Jul 18 '07 #7
ravenspoint
111 100+
All very clever. However, it seems to me everyone is thinking in base 10 and forgetting that the computer thinks in base 2. So why not just extract the bits directly, and save on all those divisions?
Expand|Select|Wrap|Line Numbers
  1.     int test = 23;
  2.     char bin[10];
  3.     char *p = &bin[8];
  4.     bin[9] = '\0';
  5.     int mask = 1;
  6.     while( mask != 512 ) {
  7.         if(  mask & test )
  8.             *p-- = '1';
  9.         else
  10.             *p-- = '0';
  11.         mask <<= 1;
  12.     }
  13.     printf("%d -> %s\n",test,bin);
  14.  
Jul 19 '07 #8
ilikepython
844 Expert 512MB
All very clever. However, it seems to me everyone is thinking in base 10 and forgetting that the computer thinks in base 2. So why not just extract the bits directly, and save on all those divisions?
Expand|Select|Wrap|Line Numbers
  1.     int test = 23;
  2.     char bin[10];
  3.     char *p = &bin[8];
  4.     bin[9] = '\0';
  5.     int mask = 1;
  6.     while( mask != 512 ) {
  7.         if(  mask & test )
  8.             *p-- = '1';
  9.         else
  10.             *p-- = '0';
  11.         mask <<= 1;
  12.     }
  13.     printf("%d -> %s\n",test,bin);
  14.  
That's pretty good, never would have thought of it, but I think this is easier:
Expand|Select|Wrap|Line Numbers
  1. bitset<8> thirty(30);
  2. cout << thirty << endl;  //  "0001 1110"
  3.  
Jul 19 '07 #9
ravenspoint
111 100+
It certainly is easier!

I had never come across that class before.

I wonder, though, if it is not easier to remember how to use the bitwise operators ( there are only two or three of them ) rather than the names and methods of all these obscure 'standard' classes.
Jul 19 '07 #10
archonmagnus
113 100+
However, it seems to me everyone is thinking in base 10 and forgetting that the computer thinks in base 2. So why not just extract the bits directly, and save on all those divisions? ...
Hence my earlier statement, "[b]ut not most efficient".

Also, it's been a long time since I used C. The OP's question asked how to do it in C. I've known about bitset in C++, but is it legal in standard C? I would have thought the method ravenspoint showed to be nearly the best you could get in standard C.
Jul 19 '07 #11
ilikepython
844 Expert 512MB
Hence my earlier statement, "[b]ut not most efficient".

Also, it's been a long time since I used C. The OP's question asked how to do it in C. I've known about bitset in C++, but is it legal in standard C? I would have thought the method ravenspoint showed to be nearly the best you could get in standard C.
Yes, you're right, i didn't pay attention that the OP mentioned C. ravenspoint's method is definately one of the best ways to do it in C. The bitset would be the C++ "way".
Jul 19 '07 #12
ravenspoint
111 100+
OK, if we are going to use my method, let's clean it up a bit and use a more natural left to right scan.
Expand|Select|Wrap|Line Numbers
  1.     int test = 23;          // number to convert
  2.     char bin[10];          // storage for converted binary coded string
  3.     char *p = bin;         // storage pointer
  4.     int mask = 256;     // start with most significant bit
  5.     while( mask ) {       // until no significance remains
  6.         if(  mask & test )    // is bit set?
  7.             *p++ = '1';     // yes
  8.         else
  9.             *p++ = '0';     // no
  10.         mask >>= 1;      //  decrease significance
  11.     }
  12.     *p = '\0';                   // null terminate string
  13.     printf("%d -> %s\n",test,bin);     // ta-da !
  14.  
Jul 19 '07 #13
Darryl
86
The problem with ravenspoint is that the number he is converting from is an int but he limits the bitmask to 256, so if someone tried it with a larger integer it would fail.

Here is my solution for 32 bit unsigned integers. Technically, though I should use limits.h to find out exactly the number of bits the particular machine/compiler is using to truly make it portable.

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.      char bits[33]="00000000000000000000000000000000";
  4.      int index=0;
  5.  
  6.      unsigned number = 23; 
  7.      unsigned copy = number;
  8.  
  9.      while(copy>0) bits[31-index++]='0'+ (1 & copy), copy>>=1;
  10.  
  11.      printf("%d -> %s\n",number , bits);
  12. }
I had a simpler method but it required bool which is not C.
Jul 19 '07 #14
ravenspoint
111 100+
The problem with ravenspoint is that the number he is converting from is an int but he limits the bitmask to 256, so if someone tried it with a larger integer it would fail.

Here is my solution for 32 bit unsigned integers. Technically, though I should use limits.h to find out exactly the number of bits the particular machine/compiler is using to truly make it portable.

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.      char bits[33]="00000000000000000000000000000000";
  4.      int index=0;
  5.  
  6.      unsigned number = 23; 
  7.      unsigned copy = number;
  8.  
  9.      while(copy>0) bits[31-index++]='0'+ (1 & copy), copy>>=1;
  10.  
  11.      printf("%d -> %s\n",number , bits);
  12. }
Problem in line #9 - the "," should be a ";" I think.

It is not good to cram so much code into one line, The compiler can keep it all straight, but it hurts my head to look at it!
Jul 19 '07 #15
Darryl
86
Problem in line #9 - the "," should be a ";" I think.
No, that's right, I think C uses the comma operator too.

It is not good to cram so much code into one line, The compiler can keep it all straight, but it hurts my head to look at it!
Yea, but I hate vertical space, I think I read once, debugging is easier and code is less likely to have errors if you can view it all at once without scrolling.
Jul 19 '07 #16
ilikepython
844 Expert 512MB
Hey, I found another way:
Expand|Select|Wrap|Line Numbers
  1. char buffer[33];
  2. int num = 30;
  3. itoa(num, buffer, 2);
  4. cout << buffer << endl;
  5.  
Jul 19 '07 #17
ravenspoint
111 100+
Hey, I found another way:
Expand|Select|Wrap|Line Numbers
  1. char buffer[33];
  2. int num = 30;
  3. itoa(num, buffer, 2);
  4. cout << buffer << endl;
  5.  
Bravissimo!

Today's lesson: RTFM

Parameters

value
Number to be converted

string
String result

radix
Base of value; must be in the range 2 – 36
Jul 19 '07 #18
Banfa
9,065 Expert Mod 8TB
Yea, but I hate vertical space, I think I read once, debugging is easier and code is less likely to have errors if you can view it all at once without scrolling.
This is true, however it does not mean cram all the code onto one line otherwise by that argument your code is most maintainable in this form

Expand|Select|Wrap|Line Numbers
  1. #include "stdio.h" 
  2. int main(){ char bits[33]="00000000000000000000000000000000"; int index=0; unsigned number = 23, copy = number; while(copy>0) bits[31-index++]='0'+ (1 & copy), copy>>=1; printf("%d -> %s\n",number , bits);}
  3.  
What that statement means is that you should keep the individual code units (functions) small enough that the fit on your screen without the need to scroll, not that you should compress your code by using shortcuts and leaving out vertical space. The first will increase maintainability and reduce the chance of putting bugs in in the first place the second will result in less maintainable harder to read code.

A good rule of thumb is "<= 1 statement per line"

In general the comma operator is not a particularly useful one and normally only sees usage in the 1st and 3rd expressions of a for loop.
Jul 20 '07 #19
Python, what does itoa mean in your code?
Aug 13 '07 #20
ilikepython
844 Expert 512MB
Python, what does itoa mean in your code?
The function means to turn an integer into a string. The name just means integer to ascii (string) (i to a).
Aug 13 '07 #21
[HTML]
Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2. #include<math.h>
  3.  
  4. int main(int argc, char *argv[]){
  5.    int num=atoi(argv[1]),r,bin[10]; // takes number from commandline argument 
  6.   for(i=0;i<10;i++)
  7.           bin[i]=3;   
  8.  i=0; 
  9.  while(num!=0){
  10.        r=num%2;
  11.        bin[i]=r;
  12.        i++: 
  13.       num=num/2; 
  14.  
  15.        }
  16.  printf("\nNumber %d in binary is..\n");
  17.  for(i=9;i>=0;i--)
  18.     if(bin[i]!=3) printf("%d",bin[i]); 
  19.  getch(); 
  20.  return 0;
  21. }

This codes shows converting number from decimal to binary.
[/HTML]
Aug 13 '07 #22
Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2. #include<math.h>
  3.  
  4. int main(int argc, char *argv[]){
  5.    int num=atoi(argv[1]),r,bin[10]; // takes number from commandline argument 
  6.   for(i=0;i<10;i++)
  7.           bin[i]=3;   
  8.  i=0; 
  9.  while(num!=0){
  10.        r=num%2;
  11.        bin[i]=r;
  12.        i++: 
  13.       num=num/2; 
  14.  
  15.        }
  16.  printf("\nNumber %d in binary is..\n");
  17.  for(i=9;i>=0;i--)
  18.     if(bin[i]!=3) printf("%d",bin[i]); 
  19.  getch(); 
  20.  return 0;
  21. }
This codes shows converting number from decimal to binary.
Aug 13 '07 #23
LXSoft
1
Without modulus operator: (works with any range of values)

Expand|Select|Wrap|Line Numbers
  1. int ttobit(int num)
  2. {
  3.     int power = log2(num);
  4.     int res[99];
  5.     int sum = 0;
  6.     int counter = 0;
  7.  
  8.     while(power >= 0)
  9.     {
  10.         sum = sum + pow(2,power);
  11.  
  12.         if(num>=sum) {res[counter] = 1;}
  13.         else
  14.         {
  15.             sum = sum - pow(2,power);
  16.             res[counter] = 0;
  17.         }
  18.         counter++;
  19.         power--;
  20.     }
  21.  
  22.     return res[99];
  23. }
  24.  
With integer representation of bytes: (only works with values under 1024)

Expand|Select|Wrap|Line Numbers
  1. int ntobit(int num)
  2. {
  3.     int power = log2(num);
  4.     unsigned long int res = 0;
  5.  
  6.     int sum = 0;
  7.  
  8.     while(power >= 0)
  9.     {
  10.         sum = sum + pow(2,power);
  11.  
  12.         if(num>=sum) { res = (res*10) + 1; }
  13.         else
  14.         {
  15.             sum = sum - pow(2,power);
  16.             res = (res*10) + 0;
  17.         }
  18.  
  19.         power--;
  20.     }
  21.  
  22.     return res;
  23. }
  24.  
Jul 11 '12 #24
bibiki
6
int numToConvert;
String rez = "";

while(numToConvert > 0)
{
rez = (numToConvert%2) + rez;
numToConvert = (int)(numToConvert/2);
}
//turn rez into an int, and there you go
Jul 11 '12 #25
whodgson
542 512MB
On a minor point (@emaghero)the C++ pow() function return a double from its two double arguments
Jul 14 '12 #26

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: David Lawson | last post by:
I know how to conver a string to an array of strings, but I need to convert an ascii string to an array of integers (really unsigned chars). Eg, $str ="ABC"; needs to convert to something...
19
by: jeff | last post by:
how do you convert form byte to Int32 while retaining the binary value of the byte array
7
by: whatluo | last post by:
Hi, all I'm now working on a program which will convert dec number to hex and oct and bin respectively, I've checked the clc but with no luck, so can anybody give me a hit how to make this done...
8
by: John A Grandy | last post by:
could someone please discuss the pros and cons of CType(MyDouble,Decimal) versus Convert.ToDecimal(MyDouble) .... and other such conversions ...
6
by: MrKrich | last post by:
I want to convert Hexadecimal or normal integer to Binary. Does VB.Net has function to do that? I only found Hex function that convert normal integer to Hexadecimal.
27
by: fdu.xiaojf | last post by:
Hi, String formatting can be used to converting an integer to its octal or hexadecimal form: '307' 'c7' But, can string formatting be used to convert an integer to its binary form ?
7
by: elliotng.ee | last post by:
I have a text file that contains a header 32-bit binary. For example, the text file could be: %%This is the input text %%test.txt Date: Tue Dec 26 14:03:35 2006...
10
by: cmdolcet69 | last post by:
Public ArrList As New ArrayList Public bitvalue As Byte() Public Sub addvalues() Dim index As Integer ArrList.Add(100) ArrList.Add(200) ArrList.Add(300) ArrList.Add(400) ArrList.Add(500)
8
by: te509 | last post by:
Hi guys, does anybody know how to convert a long sequence of bits to a bit-string? I want to avoid this: '949456129574336313917039111707606368434510426593532217946399871489' I would...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.