So I have 3 numbers. One is a char, and the other two are int16_t (also known as shorts, but according to a table I found shorts won’t reliably be 16 bits).
I’d like to concatenate them together. So say that the values of them were:
10010001
1111111111111101
1001011010110101
I’d like to end up with a long long containing:
1001000111111111111111011001011010110101000000000000000000000000
Using some solutions I’ve found online, I came up with this:
long long result;
result = num1;
result = (result << 8) | num2;
result = (result << 24) | num3;
But it doesn’t work; it gives me very odd numbers when it’s decoded.
In case there’s a problem with my decoding code, here it is:
char num1 = num & 0xff;
int16_t num2 = num << 8 & 0xffff;
int16_t num3 = num << 24 & 0xffff;
What’s going on here? I suspect it has to do with the size of a long long, but I can’t quite wrap my head around it and I want room for more numbers in it later.
To get the correct bit-pattern as you requested, you shoud use:
This will yield the exact bit pattern that you requested, 24 bits at the lsb-end left 0: