2016-08-24 3 views
2

683550(0xA6E1E)のような数値をb'\x1e\x6e\x0a\x00'に変換すると、配列のバイト数は2の倍数で、バイトオブジェクトの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 -method:

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の代わりにencoded_num_in_bytesを返します。 –

関連する問題