Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Get a bit from a byte [duplicate]

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

like image 949
luanoob Avatar asked Jan 01 '12 22:01

luanoob


People also ask

How do I access a specific bit?

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.

How do you read a byte from a bit?

8 bits = 1 byte. 1,024 bytes = kilobyte. 1,024 kilobytes = megabyte.

Can C manipulate bits?

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.

How many possible combinations in 1 byte?

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.


3 Answers

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.

like image 139
ouah Avatar answered Oct 04 '22 09:10

ouah


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

uint8_t byte;
printf("%d\n", byte & (1 << 2);
like image 26
cnicutar Avatar answered Oct 04 '22 08:10

cnicutar


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

like image 37
Francis Upton IV Avatar answered Oct 04 '22 08:10

Francis Upton IV