W1a Endian
W1a Endian
Systems Software
1
Addresses of multi-byte objects
Ex: consider the declaration
int x;
on a 32-bit machine. x takes up 4 bytes in memory.
So if x occupies the addresses 0x100 through
2
Byte Ordering
Two popular conventions
Intel is a little endian architecture
3
Little Endian
Ex: How would int x = 0x01234567 at address
0x100 be stored?
0x100 0x101 0x102 0x103
67 45 23 01
4
Origin of Big & Little Endians
Jonathan Swift, Gulliver’s Travels
A law requiring all citizens of Lilliput to break their
5
Do we care?
For most programs we don’t have to worry about endianness …
variables generally work as you would expect
Endianness matters
When transferring data over a network between machines with different
endianness
When inspecting binary data representing integers. Consider the following
IA32 instruction and its disassembly:
6
Pointers
A pointer is a variable declared to store a memory
address
declaration syntax: type *var_name;
structures
7
Pointers
Important pointer-related operators
& : address-of
* : dereference (not the same as the * used for
declarations!!!)
Example
8
Pointers and Arrays
Array name a pointer to the initial (0th) array
element
Example
int a[10];
int *ptr;
9
The sizeof operator
The sizeof operator gets a variable or a type as an input
and outputs its size in bytes.
Typical sizes on a 32-bit machine
sizeof(char) == 1
sizeof(short) == 2
sizeof(int) == 4
sizeof(int *) == 4
Lookup
10
Pointer arithmetic
Addition/subtraction operations on pointers work in
multiples of the size of the data type being pointed
to
Example
char *cp1;
int *ip1;
double *dp1;
11
Casting
Reference an object according to a different data
type from which it was created.
You can cast pointers to be pointers to other types.
This is powerful.
12
Code to print byte representation
int main(void) {
int i=12345, j;
unsigned char *p = (unsigned char *) &i;
13
show_bytes routine P. 37
typedef
typedef unsigned
unsigned char
char *byte_pointer;
*byte_pointer;
void
void show_bytes(byte_pointer
show_bytes(byte_pointer start,
start, int
int len){
len){
int
int i;
i;
for
for (i
(i == 0;
0; ii << len;
len; i++)
i++)
printf(“
printf(“ %.2x",
%.2x", start[i]);
start[i]);
printf("\n");
printf("\n");
}}
14
Problem P. 40
Consider the following three calls to show_bytes
15
Problem P. 100
Write a procedure is_little_endian that will
return 1 when compiled and run on a little-endian
machine, and will return 0 when compiled and run
on a big-endian machine. This program should
always run on any machine, regardless of its word
size.
16