I need to figure out, in python, how to convert a signed decimal to hexadecimal using 1's complement for negative values. The example results I need to get are below:
0 becomes 0000,
65.5 becomes 0041
200 becomes 00c8
-200 becomes ff37
I can easily get the positive ones using hex(), but how do I do the conversions to get the correct values for negative numbers?
Your examples are wrong. With 6.55
you actually mean 65
which leads to 0x41
. 20
becomes 0x14
, not 0xc8
because that would be 200
. The one complement for 0x20
is 0xeb
not 0x37
or 0xff37
.
To calculate the one's-complement you can use the XOR-operator . Use 0xFF
or 0xFFFF
, depending on the bit-depth of your expected data.
16-Bit:
hex(0x14 ^ 0xFFFF) -> 0xffeb
0b0000000000010100 ^
0b1111111111111111
------------------
0b1111111111101011 -> 0xffeb
8-Bit:
hex(0x14 ^ 0xFF) -> 0xeb
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.