You're not reading all the bytes of the number because you're using the wrong format specifier.
The %x
format specifier expects an unsigned int
, but you're passing a long int
. Formally, using the wrong format specifier invokes undefined behavior. Also, casting the address of one type to the address of another type besides char
and subsequently dereferencing that pointer is also undefined behavior. That being said, here's what is probably happening.
Assuming an int
is 4 bytes and a long int
is 8 bytes, that means that only the first 4 bytes of the value are read. Assuming again that your machine is little-endian, meaning that the least significant byte for an integer type comes first, the value you see is those first 4 bytes in the reverse order.
But again, this is undefined behavior. You would most likely see something very different if you passed in a floating point value when the format specifier expects an integer or vice versa. You could also crash your program if your char
array isn't properly aligned for a long
.
To fix this, change the format specifier to %lx
which expects an unsigned long int
however passing a long int
is also permissible.