tags:

views:

1783

answers:

5

Please tell me how do I print a bit, like printf("%d",bit);

Thanks a lot

+13  A: 

If bit is just an int that contains the value you want in the least significant bit, then:

printf("%d", bit & 0x1);

should do it. The & is doing a binary-AND with a number with only the first significant bit set, so you're removing all the rest of the bits in the integer.

Herms
Keep in mind that extracting one bit from a multi-byte number makes you run into endianess issues.
gnud
unwind
+2  A: 

To print the m-th bit (m from 1..16 or 32) of n:

void print_bit(n, m)
{
    printf("%d", bit & (1 << (m - 1));
}

Remove the - 1 bit if your bit counter starts at 0.

Keltia
That won't quite work. You're masking the bit you want, but you're leaving that bit in place, so you won't get 1 or 0. To always get 1 or 0 for that bit you'd need to shift the variable right, not shift the mask left.
Herms
Right, missed that, thanks.
Keltia
+8  A: 

If you need to generalize more than Herms, you could do this:

#define IsBitSet(val, bit) ((val) & (1 << (bit)))

/* ... your code ... */

printf ("%c", IsBitSet(bit, 0) ? '1' : '0');

The printf is equivalent to Herms answer as is.

If you're talking about bitfield in C, you can do this:

struct foo { int b:1; } myFoo;

printf("%c", myFoo.b ? '1' : '0');
plinth
There is a missing closing parenthesis at the end of the macro definition, no?
bortzmeyer
good catch - fixed it.
plinth
+3  A: 

Related question: http://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c is an extended discussion of single-bit access in c and c++.

dmckee
A: 

The C++ answer is easier than the C89 one, with the native bool type:

bool b = true;
std::cout << b;

C99 is quite similar:

_Bool b = 1;
printf("%d", b);
MSalters
Bools are generally not one bit in size.
Jasper Bekkers