Unit 18: Computational Thinking Number systems
Addition The rules of binary addition are: 0 + 0 = 0 0 + 1 = 1 1 + 0 = 1 1 + 1 = 0 and carry 1 When there is a carry bit, then 0 + 0 + 1 = 1 0 + 1 + 1 = 0 and carry 1 1 + 1 + 1 = 1 and carry 1
Example of Addition 0 1 1 0 1 + 1 0 1 1 1 ----------- = 1 0 0 1 0 0 0 1 1 0 1 + 1 0 1 1 1 ----------- = 1 0 0 1 0 0 1 + 1 = 0 and carry 1 0 + 1 + 1 = 0 and carry 1 1 + 1 + 1 = 1 and carry 1
Addition examples 1001 + 0110 = 1111 + 0001 = 01101100 + 00111110 =
Negative numbers We can use the “sign and magnitude” method to indicate negative numbers We can split 8 bits into One bit (the leftmost, and sign bit) is 0 for a positive number and 1 for a negative number The remaining 7 bits give the value (or magnitude) So 01111111 = + 127d, and 11111111 = - 127d
Sign/magnitude examples For example 10101011 is -43d What is -83 in binary? What is 11011101 in decimal?
Subtraction Implementing subtraction in a computer is easier if we can just use addition! The “two’s complement” method allows this. In this case a negative number is the “two’s complement” of its positive value
Two’s complement To write -28, we write out 28 in binary form 00011100 Then we invert the bits. 0 becomes 1, 1 becomes 0. 11100011 Then we add 1. 11100100 This represents -28
Two’s complement If the leftmost bit is 1, the number is negative To reverse the process, start with 11100100 Reverse the bits 00011011 Add 1 00011100 Which is decimal 28
Two’s complement example What is the binary for -30? What is 11110100 in decimal?
Addition Adding -28 to 30 (=2) 11100100 (-28) 00011110 (30) 100000010 But we only have 8 bits, so we ignore the left most (carry) bit, and the answer is 00000010 (2)
Subtraction 28 – 30 = -2 Take the two’s complement of 30 00011110 11100001 (flip the bits) 11100010 (add 1) Add this to the binary for 28 00011100 (28) 11100010 (-30) 11111110 a negative number, which we can work out to be: 00000001 (flip the bits) 00000010 (add 1, to get decimal 2)
Subtraction example Subtract 69 decimal from 12 decimal using the “twos complement” method. Show the result in binary and decimal
Subtraction example result 1100 0111 = -57 d