Python十六进制到字符串



我已经使用生成了一个十六进制字符串

x = os.system('openssl rand -hex 10')

但我想把它当作一根绳子。

我试过使用str(b0f4735701d6325fd072),但它不起作用。

还有

>>> print(x)
7a7f13f40aac84332d44
>>> print("x is of type {}nx has value {}".format(type(x), x))
x is of type <type 'int'>
x has value 0

我建议,如果您想从一个单独的过程中获得这一点,请遵循Python最佳实践并使用subprocess模块。check_output将为您提供启动过程的stdoutshlex可以为您正确解析shell命令,不要手动执行:

>>> import subprocess
>>> import shlex
>>> shlex.split('openssl rand -hex 10')
['openssl', 'rand', '-hex', '10']
>>> x = subprocess.check_output(shlex.split('openssl rand -hex 10'))
>>> x
'42bfeea1f5a1d9b96e4bn'
>>> x = x.strip()
>>> x
'42bfeea1f5a1d9b96e4b'
>>> int(x, 16)
315216711282402877075019L

为了从以0x开始的适当的十六进制文字开始,Python将其翻译为长int:

>>> 0xb0f4735701d6325fd072
835645817652699503513714L

将其传递给hex:

>>> hex(0xb0f4735701d6325fd072)
'0xb0f4735701d6325fd072L'

(您可以使用hex(0xb0f4735701d6325fd072).strip('L')从字符串中剥离L

要从字符串表示转换回long,需要将其传递给int(在Python 2中也是long)以及正确的基(在本例中为16):

>>> int('0xb0f4735701d6325fd072', 16)
835645817652699503513714L

这是一个XY问题,因为您不知道os.system做什么。

os.system运行一个shell命令并返回退出代码。您提到它正在返回0,这是因为它运行成功。

相反,您应该使用subprocess.check_output

import subprocess
hexcode = subprocess.check_output(["openssl", "rand", "-hex", "10"])

这将以字符串形式返回shell调用openssl rand -hex 10的输出,而不是其退出代码。

您可以使用os.urandom():获得随机字节

>>> import binascii, os
>>> random_bytes = os.urandom(10)
>>> random_bytes
b'xe4x19x9exbbrxe6Cxaax1ex1f'
>>> binascii.hexlify(random_bytes)
b'e4199ebb0de643aa1e1f'

如果您想在PRNG没有播种足够的数据的情况下获得异常;你可以使用ssl.RAND_bytes():

>>> import ssl
>>> ssl.RAND_bytes(10)
b'xbdHxecxc2+x03x1fx07xd0R'

openssl子流程获取随机字节:

>>> import binascii
>>> import subprocess
>>> hex_data = subprocess.check_output('openssl rand -hex 10'.split()).strip()
>>> hex_data
b'd310f3378f3e93e1f5ca'
>>> random_bytes = binascii.unhexlify(hex_data)
>>> random_bytes
b'xd3x10xf37x8f>x93xe1xf5xca'

最新更新