Python - 十进制转十六进制,反转字节顺序,十六进制转十进制
我最近在研究很多关于stuct.pack和十六进制的内容。
我想把一个十进制数转换成2字节的十六进制。然后反转这个十六进制的位顺序,最后再把它转换回十进制。
我正在尝试按照这些步骤来做……用Python。
Convert the decimal value **36895** to the equivalent 2-byte hexadecimal value:
**0x901F**
Reverse the order of the 2 hexadecimal bytes:
**0x1F90**
Convert the resulting 2-byte hexadecimal value to its decimal equivalent:
**8080**
5 个回答
1
打印格式化也可以用在字符串上。
# Get the hex digits, without the leading '0x'
hex_str = '%04X' % (36895)
# Reverse the bytes using string slices.
# hex_str[2:4] is, oddly, characters 2 to 3.
# hex_str[0:2] is characters 0 to 1.
str_to_convert = hex_str[2:4] + hex_str[0:2]
# Read back the number in base 16 (hex)
reversed = int(str_to_convert, 16)
print(reversed) # 8080!
2
请记住,'十六进制'(也就是0到9和a到f)和'十进制'(0到9)只是人类用来表示数字的方式。对机器来说,所有的数字都是以比特的形式存在。
在Python中,hex(int)这个函数会生成一个十六进制的'字符串'。如果你想把它转换回十进制:
>>> x = 36895
>>> s = hex(x)
>>> s
'0x901f'
>>> int(s, 16) # interpret s as a base-16 number
11
位移操作用来交换高八位和低八位:
>>> x = 36895
>>> ((x << 8) | (x >> 8)) & 0xFFFF
8080
将无符号短整型(H)进行打包和解包,使用相反的字节序(<>):
>>> struct.unpack('<H',struct.pack('>H',x))[0]
8080
将2字节的小端格式转换为大端格式……
>>> int.from_bytes(x.to_bytes(2,'little'),'big')
8080