gpt4 book ai didi

python - 当数字中没有字母时,bytearray.fromhex 不会转换

转载 作者:行者123 更新时间:2023-12-01 04:53:25 24 4
gpt4 key购买 nike

我正在尝试将一个数字(任意大小,可能很长)转换为其相应的字节字符串。例如,输入数字 1094795585(基数 10),即 0x41414141(基数 16),应返回“\x41\x41\x41\x41”。

目前我有:

def number_to_bytes(number):
hex_string = hex(number).rstrip("L").lstrip("0x")
return bytearray.fromhex(hex_string.decode("hex"))

当我输入数字 1094795585 (0x41414141) 时,收到错误“奇数长度字符串”。

当我输入数字 1094795584 (0x41414140) 时,出现错误“在 fromhex() arg 位置 2 中找到非十六进制数字”。

这让我觉得 Python 在 hex_string 中添加了某种不可见的字符。是这样吗?

如何实现正确的转换?

最佳答案

您不应该从十六进制解码字符串;删除 .decode('hex')称呼。您需要传递实际的十六进制数字,而不是带有基于这些数字的代码点的字节字符串。

比较差异:

>>> hex(1094795584)[2:]
'41414140'
>>> hex(1094795584)[2:].decode('hex')
'AAA@'

通过解码,您已经生成了您想要的字节 bytesarray.fromhex()生产;你可以只使用 bytesarray(hex_string.decode('hex'))在这种情况下。

您可以使用format()为您的号码生成不包含 0x 的十六进制格式前缀,也不是 L长整数的后缀:

import math

def number_to_bytes(number):
byte_count = int(math.log(number, 256)) + 1
hex_string = '{:0{}x}'.format(number, byte_count * 2)
return bytearray.fromhex(hex_string)

演示:

>>> import math
>>> def number_to_bytes(number):
... nibble_count = int(math.log(number, 256)) + 1
... hex_string = '{:0{}x}'.format(number, nibble_count * 2)
... return bytearray.fromhex(hex_string)
...
>>> number_to_bytes(1094795585)
bytearray(b'AAAA')
>>> number_to_bytes(1094795584)
bytearray(b'AAA@')

关于python - 当数字中没有字母时,bytearray.fromhex 不会转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27988235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com