Reading a binary file into different hexadecimal "types" (8 bits, 16 bits, 32 bits, ...)

I have a file containing binary data. The contents of this file are only one long line.
Example: 010101000011101010101
Initially, the content was an array of C ++ objects with the following data types:

// Care pseudo code, just for visualisation
int64 var1;
int32 var2[50];
int08 var3;

I want to skip var1and var3retrieve only the values var2in some readable decimal values. My idea was to read the byte file by byte and convert them to hexadecimal values. In the next step, I could “combine” (add) 4 of these hexadecimal values ​​to get one value int32.
Example: 0x10 0xAA 0x00 0x50 -> 0x10AA0050

My code:

def append_hex(a, b):
    return (a << 4) | b

with open("file.dat", "rb") as f:
    counter = 0
    tickdifcounter = 0
    current_byte=" "
    while True:
        if (counter >= 8) and (counter < 208):
            tickdifcounter+=1
            if (tickdifcounter <= 4):
                current_byte = append_hex(current_byte, f.read(1))
                if (not current_byte):
                    break
                val = ord(current_byte)
        if (tickdifcounter > 4):
            print hex(val)
            tickdifcounter = 0
            current_byte=""
        counter+=1
        if(counter == 209):    #209 bytes = int64 + (int32*50) + int08
            counter = 0
    print

, append_hex , , .

python, , , , - .

+4
2

struct .

Python

+1

int ord (x). , - . , :

def parseNumber(string, index):
    return ord(string[index])<<24 + ord(string[index+1])<<16 + \
           ord(string[index+2])<<8+ord(string[index+3])

, , little-endian.

, ( ), , , " struct".

+1

Source: https://habr.com/ru/post/1691228/


All Articles