簡體   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