Re: print binary representation



thanx ! have few questions about this code :)
Malcolm McLean wrote:

"Carramba" <user@xxxxxxxxxxx> wrote in message news:4604d5ca$0$488$cc7c7865@xxxxxxxxxxxxxxx
Hi!

How can I output value of char or int in binary form with printf(); ?

thanx in advance
#include <limits.h>
/*
convert machine number to human-readable binary string.
Returns: pointer to static string overwritten with each call.
*/
char *itob(int x)
{
static char buff[sizeof(int) * CHAR_BIT + 1];
why sizeof(int) * CHAR_BIT + 1 ? what does it mean?
int i;
int j = sizeof(int) * CHAR_BIT - 1;
why sizeof(int) * CHAR_BIT - 1 ? what does it mean?

buff[j] = 0;
for(i=0;i<sizeof(int) * CHAR_BIT; i++)
{
if(x & (1 << i))
buff[j] = '1';
else
buff[j] = '0';
j--;
}
return buff;
}

Call

int x = 100;
printf("%s", itob(x));

You might want something more elaborate to cut leading zeroes or handle negative numbers.
.



Relevant Pages

  • Re: print binary representation
    ... How can I output value of char or int in binary form with printf;? ... if(val & mask) ...
    (comp.lang.c)
  • Re: print binary representation
    ... How can I output value of char or int in binary form with printf;? ... something to do with ones complement or signed magnitude ...
    (comp.lang.c)
  • Re: print binary representation
    ... How can I output value of char or int in binary form with printf();? ...
    (comp.lang.c)
  • Re: print binary representation
    ... How can I output value of char or int in binary form with printf;? ... convert machine number to human-readable binary string. ... pointer to static string overwritten with each call. ...
    (comp.lang.c)
  • Re: print binary representation
    ... How can I output value of char or int in binary form with printf();? ... convert machine number to human-readable binary string. ...
    (comp.lang.c)