Object Address and Byte Ordering
Table of Contents
#include <stdio.h>
typedef unsigned char *byte_pointer;
void show_bytes(byte_pointer start, size_t len) {
size_t i;
for (i = 0; i < len; i++)
printf(" %.2x", start[i]); //line:data:show_bytes_printf
printf("\n");
}
void show_int(int x) {
show_bytes((byte_pointer) &x, sizeof(int)); //line:data:show_bytes_amp1
}
int number = 42;
int *ptr = &number;
show_int(number)
printf("Value of number: %d\n", number);
printf("Address of number: %p\n", (void *)&number);
printf("Value of ptr: %p\n", (void *)ptr);
printf("Value pointed to by ptr: %d\n", *ptr);
// 2a 00 00 00
// Value of number: 42
// Address of number: 0x16af374cc
// Value of ptr: 0x16af374cc
// Value pointed to by ptr: 42
Address #
An object’s address represents the location of its first byte in memory.
The variable ’number’ is of type int, which typically uses 4 bytes to represent it.
From the code above and Figure 1.1, we can see that the address of ’number’ (which is an int
) is 0x16af374cc
. Once the computer knows this address and the type, it can read the value.
Endianness #
Different machines have different ways of arranging object bytes.
For example, the value of ’number’ is 42
, which in hex notation is 0x0000002a
.
Big endian starts arranging from the most significant byte, while Little endian does the opposite, starting from the least significant byte. (See Figure 1.1)
int
, floats
)Try copying the code above and running it on your computer to see if your machine is Big endian or Little endian!