Numbers How does computer understand numbers Knows only
Numbers • How does computer understand numbers? – Knows only two symbols – We are mostly familiar with decimal numbers – General number representation in arbitrary base – An algorithm for converting between bases – Special case: base=2 (binary) – Is there a decimal to binary converter inside the computer? Compiler does it – Negative numbers? • Two representation conventions: sign-magnitude representation and 2’s complement representation
2’s complement • Steps involved in converting decimal to 2’s complement – Decide the number of bits (should be at least 2+integer part of log 2|N|) – Write the magnitude in binary and append zeros at the front to fill up the remaining bits (this is 2’s complement of the positive number) – Flip all bits (this is 1’s complement of the positive number) – Add 1 to it (this is 2’s complement representation of the negative number)
2’s complement • 2’s complement to decimal: – Write down the polynomial expansion in base 2 – Append a negative sign to the leading coefficient • Comparison of 2’s complement and signmagnitude – Range in sign-magnitude with n bits – Range in 2’s complement with n bits – Benefits of 2’s complement in binary arithmetic: will discuss later – All computers and calculators use 2’s complement representation
if statement if (condition) { statements } • Nested if if (condition 1) { statements 1 if (condition 2) { statements 2 } statements 3 }
/* Compute density and prevent division by zero */ class density. If { public static void main (String args[]) { double mass, volume, density; mass = 27. 2; volume = 0. 0; density=0. 0; if(volume<=0. 0) System. out. println("Density cannot be computed as the volume is zero"); if(volume>0. 0) System. out. println("Density of the liquid is: "+ mass/volume); } }
Nested if • Sometimes possible to simplify nested if if (condition 1) { if (condition 2) { statements } } • Same as if ((condition 1) && (condition 2)) { statements }
Example class example. If { public static void main(String arg[]) { int x=10, y, z; if ((x%2)==0) {System. out. println(x + “ is even. ”); if ((x%3)==0) {System. out. println(x + “ is a multiple of 6. ”); y = x/6; } z = x%6; } } }
- Slides: 7