# Lecture 003

## Machine Words

modern comuputer: k=32 bits parallel (but they handle integers as if they were 32) int: always 32 bits long (00000000000000000000000000100101)

• represent 2^31-1 (depends on signed or unsigned, there is no unsigned in c0)

• overflow happens, how to resolve?

• terminate program: no
• handling as error: destroy math reasoning
• ignore overflow bits: computes the result modulo 16 (works the same as traditional arithmetics)

• not just positive, negative numbers map to the ring as well

• int_min = -2^(k-1) = 1 and all zeros

• int_max = 2^(k-1)-1 = 0 and all ones

• -1 will be all ones

• -int_min = int_min

• -int_max() = as expected = int_min + 1

Solving represent positive and negative

string foo(int x) {
int z = i+x; //c0 always compute mod 32 at the end of each calculation.
if (x+1==z) return "Good";
}

• we don't worry about 1+x or x+1 overflowing

• function always return "Good"

• if both overflow, sometimes the program is fine

string bar(int x) {
if(x+1>x) return "Good";
else return "Strange";
}

• when we use comparison ">", ">=", "<", "<=", and "==" we need to account for overflowing

### Safe Operations in Proofing Considering Overflow (See

Here)

• copy from assumtion - fine

• subsitution - fine

• multiplication, subtraction, addition - if the sign is = is fine, else, you need need proof

• division, mod - need proof no matter what

Here

## Division and Modulus

• we want $(x/y)*y+(x%y)=x$ to hold

• and we want C0 rounds down to 0

• (Python rounds towards -\infinity)

Division by Zero: :warning: division need preconditions!

// in x/y: we requires
//@requires y!=0;
//@requires !(x==int_min() && y==-1);

• because of computer CPU architecture, we @requires !(x==int_min() && y==-1);

## Color and Bitwise Operations Bitwise color: max=0~255=2^8 bitwise: int -> int (32 bits) boolean: c0 does not evaluate int as boolean double && and ||: bool -> bool

// alpha, red, green, blue
int color = c & 0x00FF00FF //write FF to preserve and 00 to delete
int opacity = c | 0xFF000000


### XOR

return 0 when two bits are the same and one when not the same

• can be used to flip bits (where input is 1)

• https://stackoverflow.com/questions/19617248/how-to-flip-a-specific-bit-in-a-byte-in-c

• http://c0.typesafety.net/tutorial/Ints.html

## Shifts

precondition: //@requires 0 <= k && k<32 (there is no inverse or overflow shifting)

//@requires 0 <= k && k<32
x << k //left shift by k bit, overflow dropped, new bits replaced by 0
x >> k //right shift by k bit, overflow dropped new bits are the copy of leftmost bit


:warning: left and right shift behaves differently