Converting from 8 bits to 1 byte

不想你离开。 提交于 2019-12-07 09:23:29

问题


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
}

EDIT: 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!


回答1:


sum += bits[i];

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';

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

should really be

for (int i = 0; i < 8; i++)



回答2:


This should work properly, under normal situations.

What does the char[] contain? Does it contain '0', '1' instead of 0, 1?

To make sure, change line

sum += bits[i];

to

sum |= bits[i] & 1;

Also, as pointed out by Vaughn Cato in comments, you need to shift before adding.




回答3:


If any one is still interested in converting bits to bytes check out this gist. I prepared it as a sketch for the Arduino so that I can send out the electrical pulses that represent each byte. I used arrays of int instead of character but the concept is the same. Considering the size of those types, I may soon switch it to byte or char.

in particular take a look at the encodeByte and decodeByte functions

Sketch for transmitting bits gist




回答4:


#include <stdint.h>

int main()
{
    uint8_t aa=0x41; 
    printf("%c",aa);  //A
}


来源:https://stackoverflow.com/questions/13667746/converting-from-8-bits-to-1-byte

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!