我必须从一个字节中检索第一位。 为此,我将整个 1 个字节存储在 unsigned char 数组中。现在我按照下面的代码检索了第一位:
unsigned char byteArray[100];
.....
.....//some code to store 1 byte in byte array
//now 1st bit will be:
int bit=(int) byteArray[0];
我只是想确认检索第一个位所涉及的步骤是否正确?有没有更好的方法从 C 中的无符号字符数组(字节数组)中检索单个位。
最佳答案
为此,您如何(以及为什么)将字节存储在字节数组中?没必要。
无论如何,如果你想取回一个字节的第一位,你所要做的就是一位操作。
unsigned char byte = <some random value>; // your byte containing the value.
unsigned int first_bit = byte & 1; // for Least significant bit
操作byte & 1
是一个bitwise AND operation .
关于c - 如何从 C 中的字节数组(unsigned char 数组)中检索 1 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3697860/