我希望將數字如683550
(0xA6E1E)轉換爲b'\x1e\x6e\x0a\x00'
,其中數組中的字節數是2的倍數並且其中len對象的len僅爲只要它需要表示數字。使用16位塊表示數字爲一個字節
這是據我得到:
"{0:0{1}x}".format(683550,8)
捐贈:
'000a6e1e'
我希望將數字如683550
(0xA6E1E)轉換爲b'\x1e\x6e\x0a\x00'
,其中數組中的字節數是2的倍數並且其中len對象的len僅爲只要它需要表示數字。使用16位塊表示數字爲一個字節
這是據我得到:
"{0:0{1}x}".format(683550,8)
捐贈:
'000a6e1e'
使用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))
您需要輸出字節而不是字符串。 – Baz
然後只需在函數中返回encoded_num_in_bytes而不是encoded_num。 –
https://docs.python.org/3/library/struct.html#format-strings – wim
瘋狂的字節順序是怎麼回事?這不是大端或小端。 – user2357112
@ user2357112對不起。它被搞亂的原因是因爲我使用「hexdump -x」來查看文件中的字節。沒有-x就更有意義。 – Baz