1. Requirements
Ubuntu16.04
Python3.x
2. Refference
3. Sample codes (main.py)
function
import struct
'''
Charactor, Byte-order
@, native
<, little endian
>, big endian
Format, C-type, Python-type, Size[byte]
c, char, byte, 1
b, signed char, integer, 1
B, unsigned char, integer, 1
h, short, integer, 2
H, unsigned short, integer, 2
i, int, integer, 4
I, unsigned int, integer, 4
f, float, float, 4
d, double, float, 8
'''
def bwrite(data, filename):
with open(filename, "wb") as f:
for x in data:
f.write(struct.pack('b', x)) # 1byte
def bread(filename):
with open(filename, 'rb') as f:
bdata = []
while True:
bytes = f.read(1)
if bytes == b'':
break
else:
bdata.append(struct.unpack('b', bytes)[0]) # 1byte
hdata = [hex(x) for x in bdata]
return bdata, hdata
def main():
bwrite([0x00, 0x11, 0x22, 0x33], 'binary.dat')
bdata, hdata = bread('binary.dat')
print('bdata', bdata)
print('hdata', hdata)
if __name__ == "__main__":
main()
4. Results
$ python main.py
bdata [0, 17, 34, 51]
hdata ['0x0', '0x11', '0x22', '0x33']
$ hexdump binary.dat
0000000 1100 3322
0000004
Thank you.
last-samurai