繁体   English   中英

如何将十进制数转换为python中的字节列表

[英]How do you convert a decimal number into a list of bytes in python

如何将长无符号int转换为十六进制的四个字节的列表?

例...

777007543 = 0x2E 0x50 0x31 0xB7

我能想到的最简单的方法是在列表struct使用struct模块

import struct
print [hex(ord(b)) for b in struct.pack('>L',777007543)]
# ['0x2e', '0x50', '0x31', '0xb7']

它是多一点点复杂,让大写十六进制数字,但没有那么糟糕:

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”标签 - 而且现在大多数人都在使用更高版本,这里的代码说明如何这样做可以在两个版本中工作(生成大写十六进制字母):

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']

用这个:

In [1]: hex(777007543)
Out[1]: '0x2e5031b7'

你应该能够从这里重新格式化它。

使用struct模块

In [6]: import struct
In [14]: map(hex,struct.unpack('>4B',struct.pack('>L',777007543)))
Out[14]: ['0x2e', '0x50', '0x31', '0xb7']

或者,如果资本化很重要,

In [17]: map('0x{0:X}'.format,struct.unpack('>4B',struct.pack('>L',777007543)))
Out[17]: ['0x2E', '0x50', '0x31', '0xB7']

Struct模块将为您提供实际的字节:

>>> struct.pack('L',777007543)
'.P1\xb7'

字符串+结构对于这个简单的问题真的有点过分

>>> x=777007543
>>> [hex(0xff&x>>8*i) for i in 3,2,1,0]
['0x2e', '0x50', '0x31', '0xb7']
>>> [hex(0xff&x>>8*i).upper() for i in 3,2,1,0]
['0X2E', '0X50', '0X31', '0XB7']

这是使用ipython的快速比较

In [1]: import struct

In [2]: x=777007543

In [3]: timeit [hex(ord(b)) for b in struct.pack('>L',x)]
100000 loops, best of 3: 2.06 us per loop

In [4]: timeit [hex(0xff&x>>8*i) for i in 3,2,1,0]
1000000 loops, best of 3: 1.35 us per loop

In [5]: timeit [hex(0xff&x>>i) for i in 24,16,8,0]
1000000 loops, best of 3: 1.15 us per loop

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM