You must know the type of the number to extract the right number of bits - but this is only an appearance thing. By using the same 'type' for a mask you get around it
// for int
void printintbits( int x )
{
int mask = 0x01; // LSB = 1
char bs[64]; // worst case scenario is a 64 bit int
int bp = 0; // bit position
for( int i = 0; i < sizeof(int); i++ )
{
bs[bp] = (mask & x) ? '1' : '0';
bp++;
mask <<= 1;
}
bs[bp] = '\0'; // terminate string
printf( "%d = $s\n", x, bs );
}
This gives the result LSB first. For MSB first, change
bs[bp] = (mask & x) ? '1' : '0';
to
bs[sizeof(int)-bp] = (mask & x) ? '1' : '0';
2006-07-26 03:11:54
·
answer #1
·
answered by sheeple_rancher 5
·
0⤊
0⤋
#include
#include
char *strrev(char *dst, char *src) {
unsigned len = strlen(src);
int i = 0;
for(i = 0; i < len; i++) {
dst[i] = src[len-1-i];
}
dst[i] = '\0';
return dst;
}
int main(void) {
int i = 0;
unsigned num = 0;
char bit[33] = {'0'};
char bitr[33] = {'0'};
scanf("%u", &num);
// bit string created in reverse order
for( i = 0; num; i++ ) {
bit[i] = num%2 + '0';
num /= 2;
}
strrev(bitr, bit);
printf("Binary rep of %u is %s\n", num, bitr);
return 0;
}
2006-07-26 02:04:10
·
answer #2
·
answered by swami060 3
·
0⤊
0⤋
hi...........dear
would like to give u coaching for free either in c or c++ .
or maths .
what r u doin.
do bother to reply...............invincible_kimi@yahoo.com
2006-07-26 06:00:52
·
answer #3
·
answered by Anonymous
·
0⤊
0⤋