如何在Python中将十进制数转换为字节列表 [英] How do you convert a decimal number into a list of bytes in python
问题描述
如何将长无符号int转换为十六进制的四个字节的列表?
How do you turn a long unsigned int into a list of four bytes in hexidecimal?
示例...
777007543 = 0x2E 0x50 0x31 0xB7
777007543 = 0x2E 0x50 0x31 0xB7
推荐答案
我能想到的最简单的方法是使用 struct
模块列表理解:
The simplest way I can think of is to use the struct
module from within a list comprehension:
import struct
print [hex(ord(b)) for b in struct.pack('>L',777007543)]
# ['0x2e', '0x50', '0x31', '0xb7']
获取大写十六进制数字要稍微复杂一点,但还不算太糟:
It's a little bit more complicated to get uppercase hex digits, but not that bad:
import string
import struct
xlate = string.maketrans('abcdef', 'ABCDEF')
print [hex(ord(b)).translate(xlate) for b in struct.pack('>L',777007543)]
# ['0x2E', '0x50', '0x31', '0xB7']
更新
从您的评论中看来,您可能正在使用Python 3(即使您的问题没有 python-3.x标签),而且事实是当今大多数人都在使用更高版本,以下代码说明了如何做在两种版本中都可以使用(生成大写的十六进制字母):
Since from your comments it sounds like you may be using Python 3 — even though your question doesn't have a "python-3.x" tag — and that fact that nowadays most folks are using the later version, here's code illustrating how to do it that will work in both versions (producing uppercase hexadecimal letters):
import struct
import sys
if sys.version_info < (3,): # Python 2?
def hexfmt(val):
return '0x{:02X}'.format(ord(val))
else:
def hexfmt(val):
return '0x{:02X}'.format(val)
byte_list = [hexfmt(b) for b in struct.pack('>L', 777007543)]
print(byte_list) # -> ['0x2E', '0x50', '0x31', '0xB7']
这篇关于如何在Python中将十进制数转换为字节列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!