开发者

how to retrieve 1 bit from byte array(unsigned char array) in C

I have to retrieve first bit from 1 byte. For this i stored whole 1 byte in unsigned char Array. Now i retrieved first bit as per below code:

unsigned char byteArray[100];
.....
.....//some code to store 1 byte in byte array
/开发者_Go百科/now 1st bit will be:
int bit=(int) byteArray[0];

I just wanted to confirm that step involved in retrieving 1st bit is right or not? Is there any better way to retrieve single bit from unsigned char array(byte array) in C.


How (and why) do you store a byte in a byte array for this purpose? Its not necessary.

In any case, if you want to retrieve the first bit of a byte, all you have to do is one bit operation.

unsigned char byte = <some random value>;  // your byte containing the value.
unsigned int first_bit = byte & 1;  // for Least significant bit

The operation byte & 1 is a bitwise AND operation.


No, the array indexer is going to return data the size of an unsigned char, not a single bit. Use byteArray[0] & 1; - masking the value so that you only get the first bit (depending on which end is the "first"). The other end would be & 128.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜