7

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

Bence Kaulics
  • 7,066
  • 7
  • 33
  • 63

6 Answers6

20

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
  • 37,540
  • 12
  • 78
  • 101
  • Keep in mind that extracting one bit from a multi-byte number makes you run into endianess issues. – gnud Dec 08 '08 at 15:57
  • 4
    @gnud: That only applies when done against memory, using pointers. bit & 0x1 will always work, regardless of the way the value is stored in memory. – unwind Dec 08 '08 at 16:04
10

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
  • 48,267
  • 11
  • 78
  • 120
6

Related question: How do you set, clear, and toggle a single bit? is an extended discussion of single-bit access in c and c++.

Community
  • 1
  • 1
dmckee --- ex-moderator kitten
  • 98,632
  • 24
  • 142
  • 234
3

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

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

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

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Keltia
  • 14,535
  • 3
  • 29
  • 30
  • 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 Dec 08 '08 at 20:07
  • 1
    What is bit in your function? And "n" is not used. Did you mean printf("%d", n & (1 << (m - 1)) ? – Koshmaar May 07 '16 at 03:58
1

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
  • 173,980
  • 10
  • 155
  • 350
1

You can use "union":

union bitshow {
    unsigned bit1:1;
    int i;
};

int main() {
    union bitshow bit;
    cin >> bit.i;
    cout << bit.bit1;
    return 0;
}
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
  • 3
    Would that print the most significant bit, least significant bit, or something else? You can't know, because it isn't portable. – interjay Jul 11 '11 at 12:06