2015-01-16 56 views
1

我試圖將一個數字(任意大小,可能很長)轉換爲相應的字節串。例如,輸入數字1094795585(基數爲10),即0x41414141(基數爲16),應返回「\ x41 \ x41 \ x41 \ x41」。bytearray.fromhex不會在沒有字母編號的情況下轉換

目前我有:

def number_to_bytes(number): 
    hex_string = hex(number).rstrip("L").lstrip("0x") 
    return bytearray.fromhex(hex_string.decode("hex")) 

當我輸入的號碼1094795585(0x41414141),我得到的錯誤 「奇長字符串」。

當我輸入數字1094795584(0x41414140)時,出現錯誤「在位置2 fromhex()arg中找到的非十六進制數字」。

這讓我覺得Python在hex_string中添加了某種隱形字符。是這樣嗎?

我該如何實現正確的轉換?

回答

2

你應該不是從十六進制解碼字符串;請致電.decode('hex')。您需要傳入實際的十六進制數字,而不是基於這些數字的代碼點的字符串。

比較差:

>>> hex(1094795584)[2:] 
'41414140' 
>>> hex(1094795584)[2:].decode('hex') 
'[email protected]' 

通過解碼您已經產生非常字節你想bytesarray.fromhex()生產;在這種情況下,你可以使用bytesarray(hex_string.decode('hex'))

您可以使用format()產生你的電話號碼,不包含0x前綴的十六進制格式,也不是L後綴爲長整型:

import math 

def number_to_bytes(number): 
    byte_count = int(math.log(number, 256)) + 1 
    hex_string = '{:0{}x}'.format(number, byte_count * 2) 
    return bytearray.fromhex(hex_string) 

演示:

>>> import math 
>>> def number_to_bytes(number): 
...  nibble_count = int(math.log(number, 256)) + 1 
...  hex_string = '{:0{}x}'.format(number, nibble_count * 2) 
...  return bytearray.fromhex(hex_string) 
... 
>>> number_to_bytes(1094795585) 
bytearray(b'AAAA') 
>>> number_to_bytes(1094795584) 
bytearray(b'[email protected]') 
+0

如果您需要零填充,它將無法正常工作在十六進制的位置0。例如number_to_bytes(5) – Amir

+0

@Amir:啊,的確如此。糾正。 –

0

這應該工作:

import math  
def number_to_bytes(num): 
    hex_str = format(num, 'x') 
    hex_len = (int(math.log2(num)/8)+1)*2 
    return bytearray.fromhex(hex_str.zfill(hex_len)) 
相關問題