I’ve run into a small issue here. I have an unsigned char array, and I am trying to access bytes 2-3 (0xFF and 0xFF) and get their value as a short.
Code:
unsigned char Temp[512] = {0x00,0xFF,0xFF,0x00};
short val = (short)*((unsigned char*)Temp+1)
While I would expect val to contain 0xFFFF it actually contains 0x00FF. What am I doing wrong?
There’s no guarantee that you can access a
shortwhen the data is improperly aligned.On some machines, especially RISC machines, you’d get a bus error and core dump for misaligned access. On other machines, the misaligned access would involve a trap into the kernel to fix up the error — which is only a little quicker than the core dump.
To get the result reliably, you’d be best off doing shifting and or:
or:
Note that this explicitly offers big-endian (first option) or little-endian (second) interpretation of the data.
Also note the careful use of
<<and|; if you use+instead of|, you have to parenthesize the shift expression or use multiplication instead of shift:Be logical and use either logic or arithmetic and not a mixture.