2008/01/22

Bitwise Operations

Given a number in hex, 0x1234
to extract an individual digit, you need to do bitwise manipulations.

WLOG, extract the third lowest digit (third from the right):
int x = 0x1234;
int third = (x >> (2*4)) & 0xf;
assert (third == 0x2);

The ">>" shift operator moves the number to the right by the specified number of bits. So:

   01001000110100b          0x1234
>>              8        >> 0x0008
------------------       ---------
           010010b          0x0012

The "&" integer bitwise operator masks the number. So:

  00010010b           0x0012
& 00001111b         & 0x000f
-----------         --------
  00000010b           0x0002

Pointer Example

C Gold Assembly Gold Machine Notes
int a = -1; 1000: ffffffff &a = 1000
int b = -1; 1004: ffffffff &b = 1004
int* p = &a; 2000: 00001000 &p = 2000
void foo() {
*p = 5; ld $0x5, r0
ld $0x2000, r1
ld 0x0(r1), r2
st r0, 0x0(r2)
0000 0000 0005
0100 0000 2000
1012
3002
r0 ~ *p
r1 = &p
r2 = p
*p = *p
p = &c; ld $0x1004, r2
st r2, 0x0(r1)
0200 0000 1004
3201
r2 = &c
p = &c
*p = 8; ld $0x8, r0
st r0, 0x0(r2)
0000 0000 0008
3002
r0 ~ *p
*p = *p
}
TODO: insert slide show

2008/01/15

Tracing Machine Execution

Short Example


previous next

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13.

Store Example


previous next

1, 2, 3, 4, 5, 6, 7.

Mapping C to Assembly to Machine Language

Short Example

C Gold Assembly Gold Machine Notes
void foo() {
int a = 0; ld $0x0, r1 0100 0000 0000 r1 ~ a
a++; inc r1 6301
a *= 2; add r1, r1 6111
}

Store Example

C Gold Assembly Gold Machine Notes
int a = 2; 1000: 0000 0002 &a = 1000
void foo() {
ld $0x1000, r0
ld 0x0(r0), r1
0: 0000 0000 1000
1001
r0 = &a
r1 = a
a++; inc r1 6301
a *= 2; add r1, r1 6111
st r1, 0x0(r0) 3001 a = r1
}

Array Example

C Gold Assembly Gold Machine Notes
int[] a =
{0,1,2,3};
1000: 0000 0000
0000 0001
0000 0002
0000 0003
&a[] = 1000
int b = -1; 2000: ffff ffff &b = 2000
void sum() {
b = 0; ld $0x0, r2 0: 0200 0000 0000 r2 ~ b
ld $0x1000, r0 0000 0000 1000 r0 = &a
b += a[0]; ld 0x0(r0), r1
add r1, r2
1001
6112
b += a[1]; ld 0x4(r0), r1
add r1, r2
1101
6112
b += a[2]; ld 0x8(r0), r1
add r1, r2
1201
6112
b += a[3]; ld 0xc(r0), r1
add r1, r2
1301
6112
ld $0x2000, r0
st r2, 0x0(r0)
0000 0000 2000
3002
r0 = &b
b = r2
}