Convert a hexadecimal string to binary and write it to a binary file
** [Method 1] Use to_bytes () ** Because you may want to change the endian Perform in the order of character string → int → bytes (binary).
str_to_bin.py
moji = '01020304'
suuchi = int(moji,16)
bytes_big = suuchi.to_bytes(4, byteorder='big')
bytes_little = suuchi.to_bytes(4, byteorder='little')
print(bytes_big)
print(bytes_little)
wf = open('write_test.bin', 'wb')
wf.write(bytes_big)
wf.write(bytes_little)
** print result **
16909060
b'\x01\x02\x03\x04'
b'\x04\x03\x02\x01'
** [Method 2] ** Perform in the order of character string → int → bytes (binary). Since to_bytes () can only be used with python3, use struct.
str_to_bin_2.py
import struct
moji = '01020304'
suuchi = int(moji,16)
bytes_big =struct.pack(">L",suuchi)
bytes_little =struct.pack("<L",suuchi)
** [Method 3] ** If you do not want to convert to endian, you can convert from character string to bytes (binary) below.
str_to_bin_3.py
moji = '01020304'
moji_bin = binascii.unhexlify(moji)
Reference link below
[Handling hexadecimal numbers in Python](http://kaworu.jpn.org/python/Python%E3%81%A716%E9%80%B2%E6%95%B0%E3%82%92%E6%89 % B1% E3% 81% 86) Python | 2's complement (signed) int ⇔ bytes ⇔ str (hexadecimal string) Numeric-> Binary-> Hexadecimal Strings-> Binary-> Convert to Numeric in Python.
[7.1. struct — Interpret byte sequence as packed binary data] (https://docs.python.jp/3/library/struct.html) 19.8. binascii — Conversion between binary data and ASCII data
Recommended Posts