--Hexary text file-> Convert to binary file
test.txt
1234567890abcdef
↓ Binary file test.bin
For python3.2 or later in this example, use int.to_bytes
python
with open("test.txt") as fin, open("test.bin", "wb") as fout:
s = fin.read()
fout.write(int(s,16).to_bytes(len(s)//2,"big"))
It's easy to do.
The following is the code when it corresponds even if there are spaces or line breaks.
python
import re
with open('test.txt', 'r') as fin:
s = fin.read()
s = re.sub(r'[\r\n\t ]|0x', '', s)
bins = [int(a+b,16) for a, b in zip(s[::2], s[1::2])]
with open('test.bin', 'wb') as fout:
fout.write(bytearray(bins))
s = re.sub(r'[\r\n\t ]|0x', '', s)
Line breaks / tabs / half-width spaces and 0x
are deleted (replaced).
bins = [int(a+b,16) for a, b in zip(s[::2], s[1::2])]
The pairs of a and b are taken out to form a hexadecimal number and put in the list.
If you show for a, b in zip (s [:: 2], s [1:: 2])
in a little more detail, it works as follows.
In [59]: s = "1234567890abcdef"
...: for a, b in zip(s[::2], s[1::2]):
...: print(f"a={a}, b={b}")
a=1, b=2
a=3, b=4
a=5, b=6
a=7, b=8
a=9, b=0
a=a, b=b
a=c, b=d
a=e, b=f
As described in the outline
test2.txt
0x12 0x34 0x56 0x78 0x90
test3.txt
1234
56789
abc
def
Search Stack Overflow by referring to @ shiracamu's method in python2. To sum up the answers, it seems that python3 can be written as follows using codecs.
with_codecs.py
import codecs
with open('test.txt', 'r') as fin, open('test.bin', 'wb') as fout:
s = re.sub(r'[\r\n\t ]|0x', '', fin.read())
fout.write(bytearray(codecs.getdecoder("hex_codec")(s)[0])
-[Handling hexadecimal numbers in Python-Introduction to Python] 1 -[[Python] Divide the character string into two characters and store it in the list --Bagbag World] 2 --[Create a binary file in Python --Qiita] 3
Recommended Posts