Converting from 8 bits to 1 byte

13,577

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.

Share:
13,577
user200081
Author by

user200081

Updated on June 04, 2022

Comments

  • user200081
    user200081 about 2 years

    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!