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?
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";
else return "Bad";
}
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";
}
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
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);
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
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
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
-x=~x+1 (mirror the ring and slide one)
x<<k = x*2^k
x>>k = x divided by 2^k (DANGER) TODO: ask why danger
written 02 graded programming 01 due Thursday 9pm
Table of Content