I’ve got this simple piece of code:
char data[4] = { 0x13, 0x34, 0xad, 0xff };
int s = 0;
SInt32 tmp = data[s++]<<24;
printf("tmp= %x\n",tmp);
tmp += (data[s++]<<16);
printf("tmp= %x\n",tmp);
tmp += (data[s++]<<8);
printf("tmp= %x\n",tmp);
tmp += (data[s++]);
printf("tmp= %x\n",tmp);
The output I expected was
tmp= 13000000
tmp= 13340000
tmp= 1334ad00
tmp= 1334adff
instead I get
tmp= 13000000
tmp= 13340000
tmp= 1333ad00
tmp= 1333acff
May someone explain me why?
On at least some platforms Objective-C runs on, chars are signed. Possibly they are signed in objective-C by default.
What this means is that 0xad and 0xff are negative, as they have a negative sign bit (MSB).
So instead of adding 255 in the second-to-last line, you’re actually adding -1. The previous addition similarly involves a negative number.
If you change data to being “unsigned char”, this behavior should go away — though that first shift might wind up interesting.