Int to Binary Conversion

Posted on 2006-03-30
Medium Priority
Last Modified: 2013-11-15
I'm looking for a good int to binary conversion using C.
I've searched on here for some of the examples, however didn't find any I really liked..

I'd like to convert an int into a char *.
Question by:cfans
  • 2
  • 2
  • 2
  • +2

Author Comment

ID: 16338649
Is there also a way to just use printf to display an int as a binary number?
LVL 45

Expert Comment

ID: 16338690
This is a very common homework question. May we know why you need this routine?

Also ...
>I've searched on here for some of the examples, however didn't find any I really liked..
What is that you are exactly looking for? Why was the existing code not good enough?


Author Comment

ID: 16338711
Well actually it isn't that I didn't like it.. I tried using some of the examples.. and they just gave me seg faults.. can't really figure out why either.
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 11

Expert Comment

ID: 16338723
An int actually is a binary number already.

You can print it in hexadecimal with:
printf( "%x", intval );
or formatted in C-style and with all 4 bytes present:
printf( "0x%.8x", intval );

to print it to a string use:
char str[ 20 ];
sprintf( str, "0x%.8x", intval );

to get a char* of the 4 bytes of an int you can simply cast the pointer to it
char * barr =  (char *) &intval;
and access the bytes this way:
char firstByte = barr[ 0 ];
but the ordering of the bytes is processor dependant if you do it this way (little/big endian)

to do this processor independant you can use:
char barr[ 4 ];
barr[ 0 ] = (char) ( intval >> 24 );
barr[ 1 ] = (char) ( intval >> 16 );
barr[ 2 ] = (char) ( intval >>  8 );
barr[ 3 ] = (char) intval;

I'm not sure if this is what you meant.

Assisted Solution

leisner earned 400 total points
ID: 16338740
char *convert(int a)
     enum { NUM_CHARS = 33 };       /* for 32 bit ints */
     char bitarray[NUM_CHARS];
     char *p;
     unsigned value;
     value = (unsigned) a;

     p = &bitarray[NUM_CHARS - 1];
    *p ='\0';
    while(value) {
         *p = (value & 1) ? '1' : '0';
         value >>= 1;
   return strdup(p);

What algorithms did you not like?

LVL 45

Assisted Solution

sunnycoder earned 400 total points
ID: 16338778
General function to convert  would look like this

a = number
b = base (in this case, 2)

1. Start with an empty string.
2. If a is negative, add '-' to the string and negate a.
3. Add the digit (a modulus b) to the string.
4. a = a / b.
5. If a > 0 then goto 3.
6. Reverse the string.

Specifically for binary, you can simplify it significantly ...

for (all bits - note that this will be sizeof int * bits per byte)
       AND the value with 0x01 and store 1 in string if result was true else false
       right shift value by 1
reverse the string and return

To avoid reversing you can start generating the string from the other end ... AND with 1<<number of bits-1 and left shift by 1 instead of right shift.

LVL 12

Accepted Solution

rajeev_devin earned 400 total points
ID: 16339239
A very smaller recursive version

void binary(int number) {
   int remainder;
   if(number <= 1) {
      printf ("%d", number);
   remainder = number%2;
   binary(number >> 1);    
   printf ("%d", remainder);
LVL 12

Expert Comment

ID: 16341125
I apologize.

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you are like me and like multiple layers of protection, read on!
Eseutil Hard Recovery is part of exchange tool and ensures Exchange mailbox data recovery when mailbox gets corrupt due to some problem on Exchange server.
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question