Right now, what I do is this:
void print_bits(unsigned int x)
{
int i;
for(i=WORD_SIZE-1; i>=0; i--) {
(x & (1 << i)) ? putchar('1') : putchar('0');
}
printf("\n");
}
Also, it would be great to have a solution independent of word size (currently set to 32 in my example).
Ya, we can. If the array size is fixed, for example if the array's size is 6. Then you can print the values like printf(a[0]) to printf(a[5]).
To print the memory address, we use '%p' format specifier in C. To print the address of a variable, we use "%p" specifier in C programming language.
How about this:
void print2Bits(int a) {
char* table[] = {
"00",
"01",
"10",
"11"
};
puts(table[a & 3]);
}
void printByte(int a) {
print2Bits(a >> 6);
print2Bits(a >> 4);
print2Bits(a >> 2);
print2Bits(a);
}
void print32Bits(int a) {
printByte(a >> 24);
printByte(a >> 16);
printByte(a >> 8);
printByte(a);
}
I think, that's the closes you'll get to writing a binary number without a loop.
You may try itoa
. Although it is not in standard C lib, it is available in most C compilers.
void print_bits(int x)
{
char bits[33];
itoa(x, bits, 2);
puts(bits);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With