CSE 351 Sp16 Integer representation and bit operations. Q. Compute the fourth line of code. Remember that int's are 32 bits in size and are signed (2's complement). Compute the decimal value for 'result'. int x = 0xAB; int y = 17; int z = 5; int result = ~(x | y) + z; // ~(0xAB | 17) + 5 A. Let's break this down piece by piece. * Bitwise operators ~ and | operate on bit patterns or binary numerals at the level of their individual bits. To compute x|y and its complement (~), convert all values to binary. * Arithmetic operators like '+' can be done with any numerical value. Because decimal is more familiar, to do this example by hand, we convert back to decimal to do the addition. 1) Convert to binary. Prior to computing the bitwise OR (|) operator, we convert 0xAB and 17 to binary. 0xAB in binary is 1010 1011 17 in binary is 0001 0001 Keep in mind that since these are ints, the upper bits are padded with zero. Namely, we have x = 0000 0000 0000 0000 0000 0000 1010 1011 (0xAB) and y = 0000 0000 0000 0000 0000 0000 0001 0001 (17) 2) Compute x | y. 0000 ... 1010 1011 | 0000 ... 0001 0001 -------------------- 0000 ... 1011 1011 (Don't forget the padding!) 3) Flip the bits (compute ~). Just computing ~(1011 1011) is WRONG. The bitwise '~' is operating on an integer, so we have to flip the upper padded zero bits too. ~ 0000 0000 0000 0000 0000 0000 1011 1011 ----------------------------------------- 1111 1111 1111 1111 1111 1111 0100 0100 Only calculating ~(1011 1011) yields 0100 0100, which is the same least significant byte as in the binary value computed above; but this is the incorrect overall value because we are operating on 32-bit integers, not on 1-byte chars. 4) Convert back to decimal (before we add to z = 5). You won’t be expected to convert large numbers to decimal (or to binary) by hand. However, remember the trick that -x = ~x + 1 Let's use that to convert a simpler binary literal to decimal, compared to a huge negative binary value. ~(1111 .... .... 1111 0100 0100) + 1 = 0000 .... .... 0000 1011 1011) + 1 = 0000 .... .... 0000 1011 1100 The upper zero bits are no longer needed for converting to decimal. This is much simpler to convert to decimal. 1011 1100 = 0xBC = 16*11 + 12 = 188 ~x + 1 computes -x, so the actual value of x = -188. 5) Add 5. +------+ The final result is -188 + 5 = | -183 | +------+