2016-08-24 67 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。 –

相关问题