6

Possible Duplicate:
how to get bit by bit data from a integer value in c?

I have a 8-bit byte and I want to get a bit from this byte, like getByte(0b01001100, 3) = 1

Community
  • 1
  • 1
luanoob
  • 309
  • 3
  • 6
  • 8

3 Answers3

27

Firstoff, 0b prefix is not C but a GCC extension of C. To get the value of the bit 3 of an uint8_t a, you can use this expression:

((a >> 3)  & 0x01)

which would be evaluated to 1 if bit 3 is set and 0 if bit 3 is not set.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • 4
    Just helping those who may be less familiar with binary, bit 3 is actually the fourth digit from the right, i.e., 1**1**110 If you wanted to get the third digit from the right, you would right shift 2, the fifth, 4, etc. – tobahhh Mar 01 '18 at 00:27
6

First of all C 0b01... doesn't have binary constants, try using hexadecimal ones. Second:

uint8_t byte;
printf("%d\n", byte & (1 << 2);
cnicutar
  • 178,505
  • 25
  • 365
  • 392
1

Use the & operator to mask to the bit you want and then shift it using >> as you like.

Francis Upton IV
  • 19,322
  • 3
  • 53
  • 57