University of Washington Sec on 2: Integer & Floa ng Point Numbers Representa on of integers: unsigned and signed Unsigned and signed integers in C Arithme c and shi ing Sign extension Background: frac onal binary numbers IEEE floa ng point standard Floa ng point opera ons and rounding Floa ng point in C Shi ing and Sign Extension University of Washington Shi Opera ons for unsigned integers Le shi : x << y x 00000110 Shi bit vector x le by y posi ons << 3 00110000 00010000 00110000 Throw away extra bits on le >> 2 00000001 1 00011000 00000001 Fill with 0s on right Right shi : x >> y Shi bit vector x right by y posi ons Throw away extra bits on right x 11110010 Fill with 0s on le 144 << 3 10010000 00010000 10010000 60 s >> 2 00111100 00101000 00111100 Shi ing and Sign Extension University of Washington Shi Opera ons for signed integers Le shi : x << y x 01100010 Equivalent to mul plying by 2y 16 s << 3 00010000 00010000 00010000 (if resul ng value fits, no 1s are lost) Logical >> 2 00011000 24 s 00011000 00011000 Right shi : x >> y Logical shi (for unsigned values) 24 s Arithme c >> 2 00011000 00011000 00011000 Fill with 0s on le Arithme c shi (for signed values) x 10100010 Replicate most significant bit on le 16 s Maintains sign of x << 3 00010000 00010000 00010000 Equivalent to dividing by 2y 40 s Logical >> 2 00101000 00101000 00101000 Correct rounding (towards 0) requires 24 some care with signed numbers Arithme c >> 2 11101000 11101000 11101000 Undefined behavior when y < 0 or y e" word_size Shi ing and Sign Extension University of Washington Using Shi s and Masks Extract the 2nd most significant byte of an integer: First shi , then mask: ( x >> 16 ) & 0xFF x 01100001 01100010 01100011 01100100 x >> 16 00000000 00000000 01100001 01100010 00010000 00010000 00011000 00011000 00000000 00000000 00000000 11111111 ( x >> 16) & 0xFF 00000000 00000000 00000000 01100010 Extract the sign bit of a signed integer: ( x >> 31 ) & 1 need the & 1 to clear out all other bits except LSB Condi onals as Boolean expressions (assuming x is 0 or 1) if (x) a=y else a=z; which is the same as a = x ? y : z; Can be re wri en (assuming arithme c right shi ) as: a = ( (x << 31) >> 31) & y + ((!x) << 31 ) >> 31 ) & z; Shi ing and Sign Extension University of Washington Sign Extension Task: Given w bit signed integer x Convert it to w+k bit integer with same value Rule: Make k copies of sign bit: X 2 = xw 1 ,& , xw 1 , xw 1 , xw 2 ,& , x0 w k copies of MSB X " " " " " " X 2 " " " " " " w k Shi ing and Sign Extension University of Washington Sign Extension Example Conver ng from smaller to larger integer data type C automa cally performs sign extension short int x = 12345; int ix = (int) x; short int y = -12345; int iy = (int) y; Decimal Hex Binary 12345 x 30 39 00110000 01101101 12345 ix 00 00 30 39 00000000 00000000 00110000 01101101 -12345 y CF C7 11001111 11000111 iy -12345 FF FF CF C7 11111111 11111111 11001111 11000111 Shi ing and Sign Extension