Reputation: 705
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;
}
Upvotes: 1
Views: 1489
Reputation: 37
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;
}
Upvotes: 1
Reputation: 9672
uint32_t bytesTo24Bit(uint8_t hi, uint8_t mid, uint8_t low)
{
return (uint32_t(hi) << 16) | (uint32_t(mid) << 8) | low;
}
Upvotes: 3