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
For accessing a specific bit, you can use Shift Operators . If it is always a 1 that you are going to reset, then you could use an & operation. But, if it can also take 0 value, then & operation will fail as 0 & 1 = 0 . You could use | (OR) during that time.
8 bits = 1 byte. 1,024 bytes = kilobyte. 1,024 kilobytes = megabyte.
Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a byte. C language is very efficient in manipulating bits.
A byte is not just 8 values between 0 and 1, but 256 (28) different combinations (rather permutations) ranging from 00000000 via e.g. 01010101 to 11111111 . Thus, one byte can represent a decimal number between 0(00) and 255.
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.
First of all C 0b01...
doesn't have binary constants, try using hexadecimal ones. Second:
uint8_t byte;
printf("%d\n", byte & (1 << 2);
Use the & operator to mask to the bit you want and then shift it using >> as you like.
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