Post-Midterm Review

CS 301 Lecture, Dr. Lawlor

Negative two is represented as almost all ones--it's one less than negative one, which is all-ones.  So this program prints "fffffffe":
unsigned int i=-2;
std::cout<<std::hex<<i<<"\n";
return i;

(Try this in NetRun now!)

"If" in Assembly

Lots of people were very close on the "if" statement, but did something like this:
mov eax,115; "sum"
cmp eax,100
jl sum_is_small

sum_is_small:
push eax
extern print_int
call print_int
pop eax
ret

(Try this in NetRun now!)

If sum is less than 100, then the program jumps to sum_is_small.  The trouble is if the "jl" does *not* jump, then the program just keeps running along to... sum_is_small!  So this will print no matter what value sum has.  The fix is to put in a jump or return after the jl, to handle the "else" case of the if:
mov eax,115; "sum"
cmp eax,100
jl sum_is_small

jmp it_aint_small

sum_is_small:
push eax
extern print_int
call print_int
pop eax

it_aint_small:
ret

(Try this in NetRun now!)

And this is probably best written as a jump-if-greater-or-equal, like:
mov eax,115; "sum"
cmp eax,100
jge it_aint_small

push eax
extern print_int
call print_int
pop eax

it_aint_small:
ret

(Try this in NetRun now!)

Data Sizes

sizeof(char) is one byte, or 8 bits.
sizeof(void *) is four bytes, or 32 bits (on a 32-bit machine).

Memory Access

This returns 0xb3b2b1b0:
mov eax,DWORD[myInt+4] ; read this int into eax
ret
myInt:
dd 0xa3a2a1a0 ; first int, pointed to by "myInt"
dd 0xb3b2b1b0 ; second int, 4 bytes higher than "myInt"

(Try this in NetRun now!)

This returns 0xb0a3a2a1, because we're on a little-endian machine:

mov eax,DWORD[myInt+1] ; read this int into eax
ret
myInt:
dd 0xa3a2a1a0 ; first int, pointed to by "myInt"
dd 0xb3b2b1b0 ; second int, 4 bytes higher than "myInt"

(Try this in NetRun now!)