CSCI 198: Lecture 4: Data Representation
Running the program Wrong result! What happen? A run: please input two numbers: num1 = 2 num2 = 3 the sum is 5 Another run: num1 = 450 num2 = 300 the sum is 750 One more time please input two numbers: num1 = 2000000034 num2 = 9999999999 the sum is -147483615 Wrong result! What happen?
Data Representation
Decimal Number Systems Base 10 Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 e.g. 34210 = = 3 x 102 + 4 x 101 + 2 x100 = 3 x 100 + 4 x 10 + 2 x 1 = 300 + 40 + 2
Binary Number System Base 2 Digits 0, 1 e.g. 1102 = = 1 x 22 + 1 x 21 + 0 x 20 = 1 x 4 + 1 x 2 + 0 x 1 = 4 + 2 + 0 = 6
Counting in Binary Decimal Binary 0 0 1 1 2 10 3 11 4 100 5 101 6 110 0 0 1 1 2 10 3 11 4 100 5 101 6 110 7 111 Decimal Binary 8 1000 9 1001 10 1010 11 1011 12 1100 13 1101 14 1110 15 1111
Addition 0+ 0 1 + 0 0 + 1 1 + 1 1101 + 0111
How many symbol can N digit represent? 3 digit allows representing 8 numbers (symbols): 0-7 4 16: 0 – 15 N 2N
16-bit Memory Word To store number 6, use 0000000000000110 Value 0 is 0000000000000000 Largest value is 1111111111111111 = 65,535 = 216 − 1 32-bit word gives largest value > 4 billion
Number of bits How many states can be represented with 1 bits, 2 bits, 3 bits, 8 bits …. To represent N states, how many bits are needed: log2N
Character Representation 1 byte = 8 bits = 1 character? 256 possible codes with 8 bits Assign a character to each code Common assignment ASCII - American Standard Code for Information Interchange – defines first 128
ASCII Code Code Value Letter 0 Null character 1 - 31 Special Control Characters 10 \n = New line 32 Space 33-47, 58-64, 91-96 Punctuation 48 - 57 0 - 9 65 - 90 A - Z 97 - 122 a - z
Interesting ASCII Choice? Digits 0 through 9 seem strange? Digit Dec Hex 0 48 30 1 49 31 … … … 9 57 39
Unicode International language coding standard Superset of ASCII Various codes defined to use upper 128 bits for symbols in other languages
Storing Negative Values Two’s complement!
Two’s Complement Two’s complement if positive, use binary if negative, complement bits and add one e.g. −53 magnitude 00110101 complement 11001010 add 1 11001011
Overflow In 16-bit two’s complement, what happens if we add 32767 0111111111111111 + 1 0000000000000001 -------- ------------------------ −32,768 1000000000000000
Large and Small Numbers On 9-digit calculator, 999999999 + 1 = 1.0 E 9 In binary, 11111111 + 1 = 1.0 x 28 Small numbers, 0.510 = ½10 = 0.12 = 1.0 x 2-1
Real Numbers in Binary 0.11011 x 24 = 1101.1 = 8 + 4 + 1 + 0.5 = 13.5 In 16-bit word, 0 1 1 0 1 1 0 0 0 0 0 0 0 1 0 0 sign mantissa exponent
Converting Decimal to Binary Repeatedly divide by 2, recording remainders in reverse order e.g. 53 / 2 = 26 R 1 26 / 2 = 13 R 0 13 / 2 = 6 R 1 6 / 2 = 3 R 0 3 / 2 = 1 R 1 1 / 2 = 0 R 1 giving 110101
Converting Binary to Decimal Repeatedly multiply by 2 and add next bit e.g. 1101 = 1* 22 + 1*22 + 0 *21 + 1*20