Computer Arithmetic

In C, what are the results of −7 / 2 and −7 >> 1 (with an arithmetic shift) for int?

  1. A−7 / 2 is −3, and −7 >> 1 is −4
  2. BBoth are −4
  3. C−7 / 2 is −4, and −7 >> 1 is −3
Show answer and explanation

Answer: A. −7 / 2 is −3, and −7 >> 1 is −4

C defines integer division as truncating toward zero, so −3.5 becomes −3. An arithmetic right shift instead rounds toward negative infinity: shifting −7 (1111 1001) right by one gives 1111 1100 = −4. For negative numbers, shifting and dividing therefore disagree, so when compilers replace division by 2 with a shift they add correction instructions for negatives. For positive numbers the two agree.

  • A. Correct. Division truncates toward zero; the shift rounds downward.
  • B. Division truncates toward zero, giving −3.
  • C. The pairing is reversed.

Related calculators

Books on Computer Arithmetic Ad

As an Amazon Associate I earn from qualifying purchases.

More Computer Arithmetic questions

  1. In C, what is the result of subtracting 1 from 0 in a 32-bit unsigned integer (unsigned int)?
  2. How is overflow detected when adding two unsigned integers?
  3. Which correctly describes the spacing between adjacent representable floating-point values?
  4. Up to what value can IEEE 754 single precision represent every integer exactly, starting from 0?
  5. Why are monetary amounts often handled as integers in the smallest unit (one yen or one cent) rather than as binary floating point?

Comparisons in this topic