0

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 = 8; i >= 0; i--)
  {
    sum += bits[i];
    sum<<=1;
  }
  return sum;

}

int main()
{
  unsigned char bits[8]='01010111';
  unsigned int byt;
  byt = bitsToBytes(bits);
  cout << byt; //doesn't give me the right result
}

Could anyone help to get correct result? Thanks alot!

chqrlie
  • 131,814
  • 10
  • 121
  • 189

2 Answers2

3

There are multiple problems:

  • the loop in your code iterates 9 times, from 8 to 0 inclusive,
  • you read bits[8] which is an invalid access.
  • you add bits[i] which is a character with value '0' or '1', not a bit value.
  • the bits are probably shifted in the wrong order.
  • in main(), the initializer for the array is incorrect: unsigned char bits[8] = '01010111'; should be unsigned char bits[8] = "01010111";

Here is a modified version:

unsigned int bitsToBytes(unsigned char *bits) {
    unsigned int sum = 0;
    for (int i = 0; i < 8; i++) {
        sum = (sum << 1) + (bits[i] - '0');
    }
    return sum;
}

int main() {
    unsigned char bits[8] = "01010111";
    unsigned int byt;
    byt = bitsToBytes(bits);
    cout << byt;
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
2

Issues:

  1. bits is to short to accommodate 8 chars + null char
  2. shuft of the sum has to be done before adding the value
  3. Strings are enclosed in " not '
unsigned int bitsToBytes(unsigned char *bits)
{
  unsigned int sum = 0;
  while(*bits)
  {
    sum<<=1;
    sum += *bits++ - '0';
  }
  return sum;

}


int main()
{
  unsigned char bits[]="0101011101100101010101";
  unsigned int byt;
  byt = bitsToBytes(bits);
  std::cout << (unsigned)byt; //doesn't give me the right result
}

https://godbolt.org/z/PjjbGK

https://godbolt.org/z/njaKPn

0___________
  • 60,014
  • 4
  • 34
  • 74
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/218248/discussion-on-answer-by-p-j-converting-8-bits-in-binary-to-1-byte). – Samuel Liew Jul 21 '20 at 04:21