在Python中将整数转换为十六进制 [英] Convert integer to hex in Python
问题描述
在Python中,我希望将整数 3892
转换为给定格式的十六进制代码,结果 \x00\x00\x0F \x34
。这是怎么实现的?
您正在转换为数字的二进制表示,而不是十六进制表示Python将以十六进制显示字节)。使用 struct
模块
$ b 示例: struct.pack('> I',3892)
'\x00\x00\x0f4'
>>> struct.pack('> I',4314)
'\x00\x00\x10\xda'
请注意,'4'的ASCII码是0x34,如果python只是一个非空字符,它只会显示带有 \ x
可打印的字符。由于0x34是可打印的,因此python会输出 4
来代替。
'>'表示' big endian'和'I'是一个无符号的int转换(4字节)。
In Python I want to tranform the integer 3892
into a hexcode with the given format and the result \x00\x00\x0F\x34
. How can this be achieved?
You are converting to a binary representation of the number, not so much a hex representation (although Python will display the bytes as hex). Use the struct
module for such conversions.
Demonstration:
>>> struct.pack('>I', 3892)
'\x00\x00\x0f4'
>>> struct.pack('>I', 4314)
'\x00\x00\x10\xda'
Note that the ASCII code for '4' is 0x34, python only displays bytes with a \x
escape if it is a non-printable character. Because 0x34 is printable, python outputs that as 4
instead.
'>' in the formatting code above means 'big endian' and 'I' is an unsigned int conversion (4 bytes).
这篇关于在Python中将整数转换为十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!