Chris wrote:
// but reading out an int value from the array using
value = (int)data[0] + (int)data[1]*256 + (int)data[2]*65536 +
(int)data[3]*16777216;
Gives varying results. Often correct but sometimes the results is a
negative number, which i don't believe to be correct.
Is my method above for unpacking the int correct?
You should use unsigned ints for all intermediate calculations, even if
the final result is an int. Also, you have to be careful about type char
being signed or unsigned (from your message, it appears that your
compiler uses signed chars). The whole, pedantic, but safe method is:
value = (int)(
(unsigned int)(unsigned char)data[0] +
(unsigned int)(unsigned char)data[1] * 256u +
(unsigned int)(unsigned char)data[2] * 65536u +
(unsigned int)(unsigned char)data[3] * 16777216u);
The four "(unsigned int)" are probably redundant, but some pedantic
compiler may emit a warning if you don't put them. On the other hand,
the four "(unsigned char)" are essential.
If you want to be more human-friendly, you can also write:
value = (int)(
(unsigned int)(unsigned char)data[0] +
(unsigned int)(unsigned char)data[1] << 8 +
(unsigned int)(unsigned char)data[2] << 16 +
(unsigned int)(unsigned char)data[3] << 24);
The compiler would probably generate the same code, as it knows how to
optimize multiplications with shifts, but it's way more readable, IMHO.
Regards,
Alberto Barbati