字节的二进制用C [英] Bytes to Binary in C

查看:126
本文介绍了字节的二进制用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想简单地转换fget接收到的二进制字节。

I'm trying to simply convert a byte received from fget into binary.

我知道的第一字节的值是基于打印的值49。我现在需要将其转换成它的二进制值。

I know the value of the first byte was 49 based on printing the value. I now need to convert this into its binary value.

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 . . .

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

Clearly, this is not a binary value. Any help?

推荐答案

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

The problem you're having is that your assignment isn't resulting in a true or false value.

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

这得到位的值。你需要看如果该位是开还是关,如:

This gets the value of the bit. You need to see if the bit is on or off, like this:

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

这篇关于字节的二进制用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆