Data Representation Sean Barker 1 Typical Data Sizes Data Type Bytes char 1 short 2 int 4 long 8 float 4 double 8 Sean Barker 2
Numbering Systems Decimal Binary Hex 0 0 0000 1 1 0001 2 2 0010 3 3 0011 4 4 0100 5 5 0101 6 6 0110 7 7 0111 8 8 1000 9 9 1001 A 10 1010 B 11 1011 C 12 1100 D 13 1101 E 14 1110 F 15 1111 Sean Barker 3 Binary Arithmetic Sean Barker 4
• Modular Arithmetic • • – 255 (11111111) 0 Addition Unsigned numbers! 192 64 128 256. (10000000) Sean Barker 5 Signed Magnitude • • • • • • • -127 1 • 0 • 1 = 00000001, A 01, -1 = 10000001 10000001 = = 01111111 -1 127 -0 = 10000000 Sean Barker 6
Two’s Complement Two’s Complement Two’s Complement • Two’s Complement • • • • • – -1 1 • • – 0 • • • 1 = 00000001, B -1 = 11111111 From now on, unless we explicitly say otherwise, we’ll assume all integers are stored using two’s complement! This is the standard! From now on, unless we explicitly say otherwise, we’ll assume all integers are stored using two’s complement! This is the standard! 10000001 = = 01111111 127 -127 = 10000000 -128 Sean Barker 7 Signed vs Unsigned Bits& Signed& Unsigned& 0000 0 0 0001 1 1 0010 2 2 =& 0011 3 3 0100 4 4 0101 5 5 0110 6 6 0111 7 7 1000 -8 8 1001 -7 9 1010 -6 10 +/:&16& 1011 -5 11 1100 -4 12 1101 -3 13 1110 -2 14 1111 -1 15 Sean Barker 8
Sign Extension (5) 0101 00000101 (-4) 1100 11111100 Sean Barker 9 Lab 1 Warmup • Given a signed 32-bit int X, return 1 if X is positive, 0 if X is zero, and -1 if X is negative. • No loops or conditionals! • Allowed operators: ! ~ & ^ | + << >> Sean Barker 10
Overflow Danger Zone -1 255 1 0 0 192 Unsigned 64 Signed 128 -127 127 -128 Danger Zone Sean Barker 11 “Can’t Sleep” (credit: xkcd.com) Sean Barker 12
Unsigned Bugs... float sum_elements(float a[], unsigned length) { int i; float result = 0; for (i = 0; i <= length - 1; i++) { result += a[i]; } return result; } Sean Barker 13 IEEE Floating Point (IEEE 754) value = (–1) s M 2 E s' exp' frac' 1 k = 8 or 11 23 or 52 • Normalized • E = expU - bias • bias = 2 k-1 - 1 • M = 1.frac (binary) • Denormalized • Special Values • when exp = 00...00 • when exp = 11...11 • E = 1 - bias • Infinity (frac = 00...00) • M = 0.frac (binary) • NaN (frac ≠ 00...00) Sean Barker 14
Floating Point Visualization − ∞ ' + ∞ ' −Normalized' −Denorm' +Denorm' +Normalized' NaN' NaN' F0' +0' 6-bit values (3 exp, 2 frac) -15 -10 -5 0 5 10 15 Denormalized Normalized Infinity -1 -0.5 0 0.5 1 Close-up (central values) Sean Barker 15 Representing Chars Sean Barker 16
Recommend
More recommend