How to read Python hexadecimal values converted into signed

Scene: do Modbus TCP protocol in Python analog devices, read the register value is S16 (signed hexadecimal number), how can we get the correct negative value it?

code show as below:

def get_s16(val):
    if val < 0x8000:
        return val
    else:
        return (val - 0x10000)

Explanation: Since Python is not a strongly typed language, for the value of the data size is not strictly limited , so you can directly get the correct negative value by subtraction. If other strongly typed language, it is necessary in accordance with the negative complement to the principle of acquiring high value after the sign bit inversion process , to obtain the correct negative value.

Guess you like

Origin www.cnblogs.com/yqmcu/p/11104617.html