Parsing binary data into separate variables in Python? -
say open file in python contains series of binary data.
with open(sys.argv[1]) data_file: logdata = data_file.read() i want create loop saying:
for each_word in logdata: var1 = first 8 bytes var2 = next 16 bytes var3 = next 8 bytes c code generate binary file:
#include <stdio.h> #include <stdlib.h> int main(void) { file *file; int buffer = 0x03000201; int buffer2= 0x010203; file = fopen("test.bin", "wb"); if (file != null) { fwrite(&buffer, sizeof(buffer), 1, file); fwrite(&buffer2, sizeof(buffer2), 1, file); fclose(file); } return 0; } and continues until loop over, iterating through bytes of data. how possible?
use struct module, allow interpret binary data in many ways; need define types in string format documented library:
struct.unpack('=hhf255s', bytes) the above example expects native byte-order, 2 unsigned shorts, float , string of 255 characters.
your code example becomes:
for each_word in logdata: var1, var2, var3 = struct.unpack('8s16s8s', each_word) in case error typeerror: 'str' not support buffer interface, because bytes expected, passed str, convert bytes , specify encoding (in example, utf-8):
for each_word in logdata: var1, var2, var3 = struct.unpack('8s16s8s', bytes(each_word, 'utf-8')) but maybe case 8/16 byte strings long integers? in case use appropriate format struct.
edit: turns out wanted read 8 bits (not bytes), next 16 bits, next 8 bits, can read 1 (unsigned?) byte, 1 short, , byte. format string should use '=bhb' (or '=bhb' unsigned). example:
import struct open('test.bin','rb') f: var1, var2, var3 = struct.unpack('=bhb', f.read(4)) print(var1, var2, var3)
Comments
Post a Comment