我想取一个整数(这将是<= 255),以十六进制字符串表示

例:我想传入65并得到'\x41',或者255并得到'\xff'。

我尝试过用struct.pack('c',65)这样做,但它会阻塞任何超过9的东西,因为它想要接受单个字符串。


当前回答

你可以用另一种表达方式

[in] '%s' % hex(15)
[out]'0xf'

其他回答

这将把一个整数转换成带有0x前缀的2位十六进制字符串:

strHex = "0x%0.2X" % integerVariable
(int_variable).to_bytes(bytes_length, byteorder='big'|'little').hex()

例如:

>>> (434).to_bytes(4, byteorder='big').hex()
'000001b2'
>>> (434).to_bytes(4, byteorder='little').hex()
'b2010000'

使用format(),按照format-examples,我们可以做到:

>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

你也可以把任何基数的任何数字转换成十六进制。使用这一行代码,它很容易使用:

十六进制(int x (n,) . replace(“0x”、“”)

你有一个字符串n是你的数字x是这个数字的底。首先,改变它为整数,然后十六进制,但十六进制有0x在它的第一个,所以替换我们删除它。

注意,对于大值,hex()仍然有效(其他一些答案不适用):

x = hex(349593196107334030177678842158399357)
print(x)

Python 2: 0x4354467b746f6f5f736d616c3f7dl 蟒蛇3:0x4354467b746f6f5f736d616c3f7d

对于解密的RSA消息,可以执行以下操作:

import binascii

hexadecimals = hex(349593196107334030177678842158399357)

print(binascii.unhexlify(hexadecimals[2:-1])) # python 2
print(binascii.unhexlify(hexadecimals[2:])) # python 3