c - Explanation of HEX value representation and Endianess -


i working on script output sample data binary blob. i'm new intern in software field , vaguely remember idea of endianness.

i realize significant bits big-endian starts @ top , works down memory block.

if have 0x03000201 , data being parsed output 0 1 2, how happen , being done make work in terms of bits, bytes, etc.

i wondering, in example posted below, how numbers extracted form 0 1 2 when printing out data stored in variables.

for example: creating couple lines of binary blob using 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 created python script parse data:

info parse

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

big or little endianness defines how interpret sequence of bytes longer 1 byte , how store in memory. wikipedia that.

i looking understand how 0x0300020 when read 2 bytes @ time , reprinted yields 0 1 2.

you don't read 2 bytes @ time, read 4 bytes: data = f.read(4)

f.read(size) reads quantity of data , returns string. 

you unpack data using =bhb - byte, 2 bytes, byte. endianness comes play when unpack data, other io calls in code deal byte sequences.

experiment unpack() byte order, size, , alignment may @ file data hex editor of choice.

and if, after research, have concrete question, ask here.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -