python列表转字节_如何在Python中将十进制数转换为字节列表
How do you turn a long unsigned int into a list of four bytes in hexidecimal?
Example...
777007543 = 0x2E 0x50 0x31 0xB7
解決方案
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']
Update
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列表转字节_如何在Python中将十进制数转换为字节列表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java rpm包安装_rpm包安装ja
- 下一篇: python 读文件写数据库_pytho