Explanation of HEX value representation and Endianess
Question: I was working on a script to basically output some sample data as a binary
blob. I'm a new intern in the software field and vaguely remember the idea of
endianness.

I realize that the most significant bits for big-endian starts at the top and
works down the memory block.

If I have 0x03000201 and the data is being parsed to output 0 1 2, how does
this happen and what is being done to make that work in terms of bits, bytes,
etc.

I am wondering, in the example posted below, how the numbers are extracted to
form 0 1 2 when printing out the data stored in the variables.

For example: I am creating a couple lines of the binary blob using this 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;
    }
    

I then created a Python script to parse this data:

# Info About Parse

    
    
    import struct
    with open('test.bin','rb') as f:
        while True:
            data = f.read(4)
            if not data: break
            var1, var2, var3 = struct.unpack('=BHB', data)
            print(var1, var2, var3)
    


Answer: Big or little endianness defines how to interpret a sequence of bytes longer
than one byte and how to store those in memory. Wikipedia will help you with
that.

> I was really just looking to understand how 0x0300020 when read 2 bytes at a
> time and reprinted yields 0 1 2.

You don't read 2 bytes at a time, you read 4 bytes: `data = f.read(4)`

    
    
    f.read(size) reads some quantity of data and returns it as a string.
    

You unpack data using =BHB - byte, 2 bytes, byte. Endianness comes into play
only when you unpack data, all other IO calls in your code deal with byte
sequences.

Experiment with [unpack() Byte Order, Size, and
Alignment](https://docs.python.org/2/library/struct.html) You may also look at
file data with a HEX editor of your choice.

And if, after your research, you have a concrete question, ask here.

