I have this problem in getting data in binary
# Write data
f = open(path, 'wb')
start_date = [2014, 1, 1, 0, 0, 0, 0]
end_date = [2014, 2, 1, 0, 0, 0, 0]
for x in range(10):
f.write(struct.pack('B', 0))
f.write(struct.pack('I', x))
f.write(struct.pack('HBBBBBH', *start_date_binary))
f.write(struct.pack('HBBBBBH', *end_date_binary))
f.close()
# Read data
f = open(path, 'rb')
for x in range(10):
data_structure = struct.unpack_from("BIHBBBBBHHBBBBBH",
f.read(FILE_INDEX_STRUCTURE))
print(data_structure)
f.close()
Output
(0, 0, 2014, 1, 1, 0, 0, 0, 0, 56832, 7, 2, 1, 0, 0, 0)
(0, 17292800, 1, 0, 0, 0, 0, 0, 2014, 258, 0, 0, 0, 0, 0, 0)
(7, 257, 0, 0, 0, 222, 7, 2, 1, 0, 0, 0, 0, 0, 3, 0)
(0, 0, 56832, 7, 2, 1, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2014)
(0, 131989504, 258, 0, 0, 0, 0, 0, 0, 5, 0, 0, 222, 7, 1, 1)
(222, 66055, 0, 0, 0, 0, 0, 6, 0, 56832, 7, 1, 1, 0, 0, 0)
(1, 0, 0, 0, 7, 0, 0, 0, 2014, 257, 0, 0, 0, 0, 0, 56832)
(0, 0, 8, 0, 0, 222, 7, 1, 1, 0, 0, 0, 0, 222, 7, 258)
(0, 2304, 56832, 7, 1, 1, 0, 0, 0, 0, 222, 7, 2, 1, 0, 0)
Expected Result:
(0, 0, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
(0, 1, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
(0, 2, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
(0, 3, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
(0, 4, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
(0, 5, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
(0, 6, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
(0, 7, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
(0, 8, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
(0, 9, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
EDIT
Getting the type of the structure of the element, where it 'B'is 1 and 'H'equal to 2. Using these types in the same function unpack, the types are confused in the example, where it 'BH'is 3, but returns 4.
>>> struct.unpack_from("B", '')
...
struct.error: unpack_from requires a buffer of at least 1 bytes
>>> struct.unpack_from("H", '')
...
struct.error: unpack_from requires a buffer of at least 2 bytes
>>> struct.unpack_from("BH", '')
...
struct.error: unpack_from requires a buffer of at least 4 bytes