c - 如何从 C 中的字节数组(unsigned char 数组)中检索 1 位

标签 c

我必须从一个字节中检索第一位。 为此,我将整个 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/

相关文章:

C GTK通过ESC关闭后无法再次打开Dialog

c - 这个函数是如何工作的 "abcdefghijklmnopqrstuvwxyz"[rand()%26]?

c++ - 如何轻松安全地公开c服务/cpp服务

c - 如何在 Linux Kernel 3.8.0 中修改 task_struct

c - 如何用链表实现O(M^2N)的两个多项式的乘法?

c - 在多线程中传递 int 值的意外结果,C

c++ - window OS下c中UDP包的源IP

c - 无符号和有符号 int 的范围

包含笛卡尔坐标的 C 程序变量?

c++ - Win32编程隐藏控制台窗口