Apparently on your system, char
is a signed 8-bit type. Using unsigned 8-bit bytes, the 4-byte little-endian representation of 1234 would be 0xd2, 0x04, 0x00, 0x00
. But when interpreted as a signed char
on most systems, 0xd2
becomes -0x2e
.
Then the call to printf
promotes that char
to the int
with value -0x2e
, then printf
(which is not very typesafe) reads in an unsigned int
where you passed the int
. This is Undefined Behavior, but on most systems it will be the same as a static_cast
, so you get the value 0xFFFFFFD2
when trying to print the first byte.
If you stick to using unsigned char
instead of char
in these functions, you can avoid this particular problem.
(But as @jogojapan pointed out, this entire approach is not portable at all.)