将整数列表转换为十六进制表示的函数
我有一个叫做 hex2int
的函数,功能如下:
import binascii
def hex2int(hexdata):
return [ord(c) for c in binascii.unhexlify(hexdata)]
这个函数可以把像这样的字符串:
'000000000000000000030c1a314a616d72614d331f0e0603010100000000000000010101010000010305060502000000021c4179b1dcedd2a76e41210e0906040403020202020100020825528dcdf2ffe0a86f3b22130c0a08060402000000000001010203020100000000000000000000000000000203030200000000020307142c5584a8bba37c4e28160c080603000000000000000001010101010101010101000000000000000d285c93c5dac7a06c4226160f0a0704030303030403030100000000000000000002030405040301000000000000000000000000000000000000000000000007111c2732404d5a61675f5342322118100d0a080604020100'
转换成下面这样的列表:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 12, 26, 49, 74, 97, 109, 114, 97, 77, 51, 31, 14, 6, 3, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 3, 5, 6, 5, 2, 0, 0, 0, 2, 28, 65, 121, 177, 220, 237, 210, 167, 110, 65, 33, 14, 9, 6, 4, 4, 3, 2, 2, 2, 2, 1, 0, 2, 8, 37, 82, 141, 205, 242, 255, 224, 168, 111, 59, 34, 19, 12, 10, 8, 6, 4, 2, 0, 0, 0, 0, 0, 1, 1, 2, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 2, 0, 0, 0, 0, 2, 3, 7, 20, 44, 85, 132, 168, 187, 163, 124, 78, 40, 22, 12, 8, 6, 3, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 13, 40, 92, 147, 197, 218, 199, 160, 108, 66, 38, 22, 15, 10, 7, 4, 3, 3, 3, 3, 4, 3, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 4, 5, 4, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 17, 28, 39, 50, 64, 77, 90, 97, 103, 95, 83, 66, 50, 33, 24, 16, 13, 10, 8, 6, 4, 2, 1, 0]
现在我想写一个反向的函数 int2hex
,它可以把这个列表变回最初的字符串。
我现在写的代码是:
def int2hex(intdata):
return binascii.hexlify(''.join([hex(i) for i in intdata]))
但是这个代码没有返回正确的结果。你能告诉我我哪里出错了吗?
4 个回答
3
在编程中,有时候我们会遇到一些问题,特别是在使用某些工具或库的时候。这些问题可能会让我们感到困惑,尤其是当我们刚开始学习编程的时候。比如,有人可能会在使用某个特定的功能时,发现它没有按照预期工作。这时候,我们就需要去查找解决方案,看看别人是怎么处理类似问题的。
在这个过程中,StackOverflow是一个非常有用的资源。这里有很多程序员分享他们的经验和解决方案。你可以在这里找到许多关于编程问题的讨论,看到别人是如何解决问题的,甚至可以向他们提问,寻求帮助。
总之,遇到问题时,不要气馁,利用好这些资源,慢慢积累经验,你会变得越来越熟练的。
print ''.join("%02x"%my_int for my_int in my_list)
4
在没有使用列表推导式的情况下,适用于Python 2.7及以上版本:
binascii.hexlify(bytearray(my_list))
在Python 2.6中,它需要一个“只读”的缓冲区,这和bytearray不一样:
binascii.hexlify(buffer(bytearray(my_list)))
4
只需要使用 format()
这个函数:
''.join(format(my_int, '02x') for my_int in my_list)
这个函数会把每个整数格式化成2位的小写十六进制数,如果这个数小于16,它前面会加个0。