## 利用python进行负数向二进制和十六进制的相互转换

负数十六进制 = hex ( 负数  &  0xFF....FF )  (注意：几个F取决于数据类型的范围，如int数据类型取0xFFFFFFFF)

neg十六进制 = hex(-45054 & 0xFFFFFFFF) = hex(4294922242) = 0xFFFF5002

neg二进制 = bin(neg十六进制）= bin(0xFFFF5002) = 11111111111111110101000000000010

import struct

s_hex_neg = pack('i', neg) = '\x02P\xff\xff'       //这里是十六进制的可见字符ascii表示

hex_neg = binascii.hexlify(s_hex_neg) = 0250ffff

hex_neg[::-1] = ffff0520

neghex=0xFFFF0520，是int数据类型

1.十六进制转为二进制

negbin = bin(neghex)='0b11111111111111110000010100100000'

2.十六进制还原为负数

neghex_s = hex(neghex)[2:-1] = 'ffff0520'

neghex_s=neghex_s[::-1] = '0250ffff'

neghex_pack=binascii.unhexlify(neghex_s)='\x02P\xff\xff'

neg=struct.unpack('i', neghex_pack)=(-45054,)

neg_bin_s='11111111111111110000010100100000'，字符串类型

1.二进制向十六进制转化

neg_bin_list=[]

for i in range(0, len(neg_bin_s), 4):

neg_bin_list.append(neg_bin_s[i:i+4])

neg_bin_list=['1111', '1111', '1111', '1111', '0000', '0101', '0010', '0000']

hex_map={}

for i in range(0,16):
hex_map[bin(i)[2:].zfill(4)]=hex(i)[2:]

neg_hex_s=''

for i in neg_bin_list:

neg_hex_s += hex_map[i]

2.二进制还原成负数

neghex_s=neg_hex_s[::-1] = '0250ffff'

neghex_pack=binascii.unhexlify(neghex_s)='\x02P\xff\xff'

neg=struct.unpack('i', neghex_pack)=(-45054,)