从8位转换为1个字节 [英] Converting from 8 bits to 1 byte
问题描述
我有一个8位的字符串,我想将其转换为1个字节.我不确定为什么我的功能不能正常工作.我有8位存储到8个未签名字符的数组中.到目前为止,这是我的方法:
I have a string of 8 bits and I want to convert it into 1 byte. I am not sure why my function is not working properly. I have 8 bits stored into an array of 8 unsigned chars. This is my method so far:
unsigned int bitsToBytes(unsigned char *bits)
{
unsigned int sum = 0;
for(int i = 7; i >= 0; i--)
{
sum += bits[i];
sum<<=1;
}
return sum;
}
int main()
{
unsigned char bits[8];
unsigned int byt;
byt = bitsToBytes(bits);
cout << byt; //doesn't give me the right result
}
我的位数组在数组中包含"1"和"0"!抱歉,不清楚.
My array of bits contains '1' and '0' in the array! Sorry for not being clear.
也许有人知道我在哪里出错了吗?我不确定为什么我的位没有正确转换为字节.有人可以帮忙吗?谢谢!
Might anyone know where I went wrong in this? I'm not sure why my bits aren't converting to bytes properly. Could anyone help? Thanks!
推荐答案
sum += bits[i];
如果您尝试转换C 字符串(例如,"1010101"
),则此代码会添加char的代码表值(ASCII,UTF-8,无论您使用哪种编码) (例如48和49),而不是1
和0
.您应该将其重写为
If you're trying to convert a C string (for example, "1010101"
), this code adds the codetable value (ASCII, UTF-8, whichever encoding you have) of the char (for example, 48 and 49), not 1
and 0
. You should rewrite this as
sum += bits[i] - '0';
此外,您不会初始化bits
数组-在初始化之前使用其内容会导致未定义的行为,因此您可以弄清任何事情发生.
Also, you don't initialize the bits
array - using its contents before initialization results in undefined behavior, so you can expact anything to happen.
此外,您的代码逻辑有缺陷-一种,您必须在添加二进制数字之前向左移动.第二,您正在向后遍历字符串;线
Furthermore, your code logic is flawed - One, you have to do the left shift before adding the binary digit. Two, you're traversing the string backwards; the line
for (int i = 7; i >= 0; i--)
应该是
for (int i = 0; i < 8; i++)
这篇关于从8位转换为1个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!