Re: print binary representation
- From: Carramba <user@xxxxxxxxxxx>
- Date: Sat, 24 Mar 2007 12:41:35 +0100
thanx ! have few questions about this code :)
Malcolm McLean wrote:
why sizeof(int) * CHAR_BIT + 1 ? what does it mean?
"Carramba" <user@xxxxxxxxxxx> wrote in message news:4604d5ca$0$488$cc7c7865@xxxxxxxxxxxxxxxHi!#include <limits.h>
How can I output value of char or int in binary form with printf(); ?
thanx in advance
/*
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];
int i;why sizeof(int) * CHAR_BIT - 1 ? what does it mean?
int j = sizeof(int) * CHAR_BIT - 1;
.
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.
- Follow-Ups:
- Re: print binary representation
- From: Joachim Schmitz
- Re: print binary representation
- References:
- print binary representation
- From: Carramba
- Re: print binary representation
- From: Malcolm McLean
- print binary representation
- Prev by Date: Re: newbie question: whats wrong with my code?
- Next by Date: Re: print binary representation
- Previous by thread: Re: print binary representation
- Next by thread: Re: print binary representation
- Index(es):
Relevant Pages
|
|