2016-08-24 35 views
2

我希望將數字如683550(0xA6E1E)轉換爲b'\x1e\x6e\x0a\x00',其中數組中的字節數是2的倍數並且其中len對象的len僅爲只要它需要表示數字。使用16位塊表示數字爲一個字節

這是據我得到:

"{0:0{1}x}".format(683550,8) 

捐贈:

'000a6e1e' 
+0

https://docs.python.org/3/library/struct.html#format-strings – wim

+0

瘋狂的字節順序是怎麼回事?這不是大端或小端。 – user2357112

+0

@ user2357112對不起。它被搞亂的原因是因爲我使用「hexdump -x」來查看文件中的字節。沒有-x就更有意義。 – Baz

回答

2

使用.tobytes - 方法:

num = 683550 
bytes = num.to_bytes((num.bit_length()+15)//16*2, "little") 
+0

爲您的答案輸出[hex(i)for i]給出['0x1e','0x6e','0xa','0x0']。我正在尋找['0x6e','0x1e','0x0','0xa'] – Baz

+0

,所以你真的想要這種混合的小大端的東西。所以看到我更新的答案。 – Daniel

+0

對不起@丹尼爾,你原來的回答確實是對的。我正在使用「hexdump -x」來查看正在切換的文件。我用正確的字節編輯了我的問題。 – Baz

0

使用python3:

def encode_to_my_hex_format(num, bytes_group_len=2, byteorder='little'): 
    """ 
    @param byteorder can take the values 'little' or 'big' 
    """ 
    bytes_needed = abs(-len(bin(num)[2: ]) // 8) 

    if bytes_needed % bytes_group_len: 
    bytes_needed += bytes_group_len - bytes_needed % bytes_group_len 

    num_in_bytes = num.to_bytes(bytes_needed, byteorder) 
    encoded_num_in_bytes = b'' 

    for index in range(0, len(num_in_bytes), bytes_group_len): 
    bytes_group = num_in_bytes[index: index + bytes_group_len] 

    if byteorder == 'little': 
     bytes_group = bytes_group[-1: -len(bytes_group) -1 : -1] 

    encoded_num_in_bytes += bytes_group 

    encoded_num = '' 

    for byte in encoded_num_in_bytes: 
    encoded_num += r'\x' + hex(byte)[2: ].zfill(2) 

    return encoded_num 

print(encode_to_my_hex_format(683550)) 
+0

您需要輸出字節而不是字符串。 – Baz

+0

然後只需在函數中返回encoded_num_in_bytes而不是encoded_num。 –