- import struct
-
-
- def intToHex(num): # int转16进制
- return hex(num)[2:].upper()
-
- def hexToInt(hexString): # 16进制转int
- return int(hexString, 16)
-
- def floatToHex(floatValue): # float转16进制
- return struct.pack('>f', floatValue).hex().upper()
-
- def hexToFloat(hexString): # 16进制转float
- return struct.unpack('>f', bytes.fromhex(hexString))[0]
-
- def doubleToHex(doubleValue): # double转16进制
- return struct.pack('>d', doubleValue).hex().upper()
-
- def hexToDouble(hexString): # 16进制转double
- return struct.unpack('>d', bytes.fromhex(hexString))[0]
-
- if __name__ == '__main__':
- print(intToHex(1000), hexToInt("3E8"))
- print(floatToHex(1.0), hexToFloat("3F800000"))
- print(doubleToHex(1.00), hexToDouble("3FF0000000000000"))
结果:
- bytesNumber = 6 # 传入几个字节
-
- # 传入bytesNumber个字节十六进制字符串,返回int类型
- def str_to_signed_int_bytes(data: str):
- int_data = int(data, 16)
- if int_data >= (2**(bytesNumber*8)-2)/2:
- int_num = int_data - (2**(bytesNumber*8)-2)
- else:
- int_num = int_data
- return int_num
-
- # 传入int类型字符串,返回bytesNumber个字节带符号十六进制数据字符串
- def signed_int_to_str_bytes(int_num: int):
- if int_num < 0:
- int_temp = (2**(bytesNumber*8)-2) + int_num
- else:
- int_temp = int_num
- str_hex = '{:04X}'.format(int_temp)
- return str_hex.zfill(bytesNumber*2)
-
- if __name__ == '__main__':
- print(str_to_signed_int_bytes('FFFFFF587239'))
- print(signed_int_to_str_bytes(-10980805))
测试结果:
另一种写法:
- def Sign_IntTo2ByteString(num): # 有符号,int转2字节字符串
- return bytes.hex((num).to_bytes(2,'big',signed=True)).zfill(4)