1

I'm using C++ to parse binary data from files. Each byte gets stored in a char array, at least when working from cplusplus.com's example. The issue here is that my data source uses 24-bit values, so bytes have to be combined.

Here is a very simple example. The desired output is AABB but the actual output is 165 due to it doing addition.

#include <iostream>
using namespace std;

int main() {
    unsigned char one = 0xAA;
    unsigned char two = 0xBB;
    unsigned int sum = one + two;
    cout << hex << sum << "\n";
    return 0;
}
spacer GIF
  • 626
  • 5
  • 19

2 Answers2

3
uint32_t bytesTo24Bit(uint8_t hi, uint8_t mid, uint8_t low)
{
  return (uint32_t(hi) << 16) | (uint32_t(mid) << 8) | low;
}
robthebloke
  • 9,331
  • 9
  • 12
  • Side note: This [shouldn't depend on endianness](https://stackoverflow.com/a/7184905/10957435), which is good news. Although this is talking about C. I'd imagine it'd be the same, though. –  Jul 23 '19 at 02:10
  • Using a 24 bit bitfield in a struct based on `int_fast32_t` instead of `uint32_t` saves up to 25% space. –  Jul 23 '19 at 02:57
1

A very simple solution to this would be to use the 'left shift equals' <<= operator.

an example of what your code could do would be:

int main() {
    unsigned char one = 0xAA;
    unsigned char two = 0xBB;
    unsigned int sum = one;
    sum <<= 8; //This shifts the value of AA 8 bits to the left
    sum += two;

    cout << hex << sum << "\n";
    return 0;
}
mattloulou
  • 37
  • 5
  • `unsigned int`'s size is implementation defined and may be as low as 16 bits. OP asked for 24 bit int, which is not guaranteed to fit in `unsigned int`. –  Jul 23 '19 at 02:52