So my code has in it the following:
unsigned short num=0; num=*(cra+3); printf("> char %u\n",num);
cra is a char*
The problem is that it is getting odd output, sometimes outputting numbers such as 65501 (clearly not within the range of a char). Any ideas?
Thanks in advance!
Apparently
*(cra+3)is acharof value'\xdd'. Since acharis signed, it actually means -35 (0xddin 2’s complement), i.e. 0x…fffffdd. Restricting this to 16-bit gives 0xffdd, i.e. 65501.You need to make it an
unsigned charso it gives a number in the range 0–255:Note:
1. the signedness of
charis implementation defined, but usually (e.g. in OP’s case) it is signed.2. the ranges of
signed char,unsigned charandunsigned shortare implementation defined, but again commonly they are -128–127, 0–255 and 0–65535 respectively.3. the conversion from
signed chartounsigned charis actually -35 + 65536 = 65501.