Endianness refers to how bytes of a word(2 bytes) is ordered within the memory.
8 bits = byte16 bits = word
Big Endian Systems are the systems in which the MSB (Most Significant Byte) of the word is stored in the smallest address given and LSB (Least Significant Byte) is stored in the largest.
Little Endian Systems are the systems in which the MSB (Most Significant Byte) of the word is stored in the largest address given and LSB (Least Significant Byte) is stored in the smallest.
Little Endian Systems are the systems in which the MSB (Most Significant Byte) of the word is stored in the largest address given and LSB (Least Significant Byte) is stored in the smallest.
#include <stdio.h> int main() { unsigned int i = 1; char *c = (char*)&i; printf("i addr %p c %d addr %p\n", &i, *c, c); if (*c) { printf("Little endian"); } else { printf("Big endian"); } return 0; }
Output:
i addr 0x7ffc83552e3c c 1 addr 0x7ffc83552e3c
Little endian
|
In the above program, int is 4 bytes, so i is stored as (MSB) 0(0x100), 0(0x101), 0 (0x102), (LSB)1(0x103) if it is big-endian machine. In little-endian machine, i is stored as (MSB) 0(0x103), 0(0x102), 0 (0x101), (LSB)1(0x100).
If the above program runs in little-endian machine, &i will have 0x100 which will be typecasted into char *. This char * is 1 byte, so it stores only the first address's (0x100) value.
#include <stdio.h> void memory_rep(char *val, int n) { int i; for (i = 0; i < n; i++) { printf(" %.2x", val[i]); printf(" %.2x", &val[i]); } printf("\n"); } int main() { int value = 0x12345678; memory_rep((char *)&value, sizeof(value)); return 0; }
Output:
78 fff3756c 56 fff3756d 34 fff3756e 12 fff3756f
|
<will update with diagram soon>
Comments
Post a Comment