C 中的字节到二进制

问题描述 投票:0回答:7

我试图简单地将从 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 . . .

显然,这不是一个二进制值。有什么帮助吗?

c binary byte bit
7个回答
16
投票

您遇到的问题是您的分配不会产生 true 或 false 值。

bits[i] = byte & (mask << i);

这获取了该位的值。您需要查看该位是打开还是关闭,如下所示:

bits[i] = (byte & (mask << i)) != 0;

7
投票

改变

bits[i] = byte & (mask << i);

bits[i] = (byte >> i) & mask;

bits[i] = (byte >> i) & 1;

bits[i] = byte & 1;
byte >>= 1;

4
投票

多种方法中的一种:

#include <stdio.h>
#include <limits.h>

int main(void) {
    int i;
    char bits[CHAR_BIT + 1];
    unsigned char value = 47;

    for (i = CHAR_BIT - 1; i >= 0; i -= 1) {
        bits[i] = '0' + (value & 0x01);
        value >>= 1;
    }

    bits[CHAR_BIT] = 0;

    puts(bits);

    return 0;
}

1
投票

您可能会注意到,您的输出有几个 1 和 0,但也有 2 的幂,例如 32。这是因为在使用掩码隔离所需的位后,您仍然需要将其位移到最小位 -有效数字,以便它显示为 1。或者您可以使用其他帖子建议的内容,而不是对结果进行位移(例如 00001000),您可以简单地使用 (result != 0) 来获取1 或 0,因为在 C 中, false 为 0,并且诸如 != 之类的比较将返回 1 作为 true(我认为)。


0
投票
#include<Stdio.h>
#include <limits.h>
void main(void) {
    unsigned char byte = 49;// Read from file
    unsigned char mask = 1; // Bit mask
    unsigned char bits[8];
    int i, j = CHAR_BIT-1;
          // Extract the bits
    for ( i = 0; i < 8; i++,j--,mask = 1) {
    // Mask each bit in the byte and store it
    bits[i] =( byte & (mask<<=j))  != NULL;
    }
    // For debug purposes, lets print the received data
    for (int i = 0; i < 8; i++) {
       printf("%d", bits[i]);
   }
   puts("");
}

0
投票

如果您使用的是带有 GNU C 库版本 2.35 或更高版本的系统,您可以使用

%b
转换规范将字节转换为二进制,如下所示:

#include <stdio.h>

int main() {
    unsigned char byte = 49;
    printf("binary rep. of char byte 49: %#b \n", byte);
    printf("Enter a decimal value between 0 & 255:\n");
    scanf("%d", &byte);
    printf("binary rep of entered decimal value: %#b \n", byte);
}

验证您拥有

glibc
> 2.34 的版本:

ldd --version

编译:

gcc -o b-con b-con.c

也许有一天,

scanf
也会有二进制转换?


-1
投票

这个添加代替它将起作用:

bits[i]= byte & (mask << i); 
bits[i] >>=i;
© www.soinside.com 2019 - 2024. All rights reserved.