683550
(0xA6E1E)のような数値をb'\x1e\x6e\x0a\x00'
に変換すると、配列のバイト数は2の倍数で、バイトオブジェクトのlenは番号を表す必要がある場合は限ります。私が得たとして16ビットブロックを使用してバイトとして表現する
は、これは限りある:
"{0:0{1}x}".format(683550,8)
寄付:
'000a6e1e'
683550
(0xA6E1E)のような数値をb'\x1e\x6e\x0a\x00'
に変換すると、配列のバイト数は2の倍数で、バイトオブジェクトのlenは番号を表す必要がある場合は限ります。私が得たとして16ビットブロックを使用してバイトとして表現する
は、これは限りある:
"{0:0{1}x}".format(683550,8)
寄付:
'000a6e1e'
使用.tobytes
-method:
num = 683550
bytes = num.to_bytes((num.bit_length()+15)//16*2, "little")
使用の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の代わりにencoded_num_in_bytesを返します。 –
https://docs.python.org/3/library/struct.html#format-strings – wim
クレイジーバイトオーダーはどうですか?これはビッグエンディアンでもリトルエンディアンでもありません。 – user2357112
@ user2357112すみません。私が "hexdump -x"を使用してファイル内のバイトを表示していたため、それがうまくいかなかったのです。 -xを指定しないと意味がなくなります。 – Baz