We are running programs where values of type int are 32 bits. They are represent
ID: 3877899 • Letter: W
Question
We are running programs where values of type int are 32 bits. They are represented in two's complement, and they are right-shifted arithmetically. Values of type unsigned are also 32 bits.
We generate arbitrary values x and y, and convert them to unsigned values as follows:
/* Create some arbitrary values •/
int x = random();
int y = random();
/* Convert to unsigned */
unsigned ux = (unsigned) x;
unsigned uy = (unsigned) y;
For each of the following C expressions, you are to indicate whether or not the expression always yields 1.
If it always yields 1, describe the underlying mathematical principles.
Otherwise, give an example of arguments 'that make it yield 0.
A. (x<y) == (-x>-y)
B. ((x+y) << 4) + y-x == 17*y+15*x
C. ~x+~y+1 == ~(x+y)
D. (ux-uy) == -(unsigned)(y-x)
E. ((x >> 2) << 2) <= x
Explanation / Answer
Option A is false, because 1 > INT_MIN != -1 < -INT_MIN
Option B yields 1 always, the mathematical principle is ring properties of 2’s complement arithmetic. It is true.
Let take LHS == ((x+y) << 4) + y-x
= ((x+y) * 0x10000) + y-x
= ((x+y) * 16) + y-x
= 17 * y + 15 * x = RHS
Option C is false, for example apply x and y value to the equation. ~(1100) + ~(1100) != ~(11000)
Option D is true, the mathematical principle is isomorphism between 2’s complement and unsigned arithmetic. Unsigned and signed Integer bit pattern is identical completely. So, it is true.
Option E is true, Shift right (>>) fill zero by the lower bits. But old integer is decreased to one, even the integer is not changed.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.