Casting a short from a char array

c, casting

Solution

There's no guarantee that you can access a `short` when 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:

val = *(Temp+1) << 8 | *(Temp+2);

or:

val = *(Temp+2) << 8 | *(Temp+1);

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:

val = (*(Temp+1) << 8) + *(Temp+2);
val = *(Temp+1) * 256 + *(Temp+2);

Be logical and use either logic or arithmetic and not a mixture.

Problem

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?

Original source