2009-11-05 68 views
7

我试图简单地将从fget接收到的字节转换为二进制。字节到二进制在C

我知道基于打印值的第一个字节的值是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 . . . 

显然,这不是一个二进制值。任何帮助?

回答

16

您遇到的问题是,你的任务是不是导致true或false值。

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

这得到了该位的值。你需要看如果该位被打开或关闭,像这样:

bits[i] = (byte & (mask << i)) != 0; 
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; 
} 
5

变化

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

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

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

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

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

-1

这除了代替,将工作:

bits[i]= byte & (mask << i); 
bits[i] >>=i; 
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(""); 
}