2015-06-05 40 views

回答

3

只要打電話給bytes構造。

由於文檔說:

… constructor arguments are interpreted as for bytearray() .

如果你遵循這個鏈接:

If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256 , which are used as the initial contents of the array.

所以:

>>> list_of_values = [55, 33, 22] 
>>> bytes_of_values = bytes(list_of_values) 
>>> bytes_of_values 
b'7!\x16' 
>>> bytes_of_values == '\x37\x21\x16' 
True 

當然的值不會是\x55\x33\x22 ,因爲\x意味着十六進制,並且十進制值55, 33, 22是十六進制值37, 21, 16。但是,如果你有十六進制值55, 33, 22,你會得到準確的輸出你想要的:

>>> list_of_values = [0x55, 0x33, 0x22] 
>>> bytes_of_values = bytes(list_of_values) 
>>> bytes_of_values == b'\x55\x33\x22' 
True 
+0

錯誤的十進制/十六進制輸入和輸出的良好捕獲。 –

0
struct.pack("b"*len(my_list),*my_list) 

我想將工作

>>> my_list = [55, 33, 22] 
>>> struct.pack("b"*len(my_list),*my_list) 
b'7!\x16' 

,如果你想詛咒你需要使它十六進制列表

>>> my_list = [0x55, 0x33, 0x22] 
>>> struct.pack("b"*len(my_list),*my_list) 
b'U3"' 

在所有情況下,如果該值有一個ASCII表示,當您嘗試打印或看它會顯示它...

+0

這是接近我想,我得到這個錯誤'struct.error:字節格式要求-128 <=號< = 127'你能幫忙嗎? – Startec

+1

@Startec「b」格式表示有符號字節[-128,127]。你想爲_un_signed字節使用大寫字母'B'[0,255]。 –

+2

你不需要爲此使用'struct'。 – abarnert

相關問題