我正在尝试将从 fget 接收到的字节简单地转换为二进制。
根据打印值,我知道第一个字节的值为 49。我现在需要将其转换为其二进制值。
unsigned char byte = 49;// Read from file
unsigned char mask = 1; // Bit mask
unsigned char bits[8];
// Extract the bits
for (int i = 0; i < 8; i++) {
// Mask each bit in the byte and store it
bits[i] = byte & (mask << i);
}
// For debug purposes, lets print the received data
for (int i = 0; i < 8; i++) {
printf("Bit: %d\n",bits[i]);
}
这将打印:
Bit: 1
Bit: 0
Bit: 0
Bit: 0
Bit: 16
Bit: 32
Bit: 0
Bit: 0
Press any key to continue . . .
显然,这不是二进制值。有帮助吗?
最佳答案
您遇到的问题是您的分配没有产生 true 或 false 值。
bits[i] = byte & (mask << i);
这将获取该位的值。您需要查看该位是打开还是关闭,如下所示:
bits[i] = (byte & (mask << i)) != 0;
关于c - C中的字节到二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1682996/