Skip to main content

Subsection 12.6.4 Shifting a Signed Value Is Not Quite Dividing It

accel_test.c converts with (ACC_FS * raw * MILLI) >> ACC_REGISTERWIDTH. The variables are int16_t, and the large intermediate product (up to about ±131 million) exists only inside the arithmetic, which C carries out in a wider integer type before the shift brings the result back within ±2000. On a signed value, our compiler’s >> is an arithmetic shift: it shifts the sign bit back in at the top, and it rounds toward negative infinity (it is a floor). The C standard leaves that choice to the implementation, and arm-none-eabi-gcc, like every compiler you are likely to meet, shifts the sign bit back in. Integer division with / rounds toward zero instead. For positive values the two agree; for negative values they can differ by one.
That difference is visible in this chapter’s own numbers, because the program multiplies by 4000 before shifting by 16, and the product is usually not a multiple of 2¹⁶. Take a raw reading of −64 (0xFFC0), which is one step in normal mode: the product is 4 × (−64) × 1000 = −256000, which is −3.90625 of 2¹⁶, the chapter’s own step size. The shift floors it to −4, so CoolTerm prints −4 mg; a hand check with / or a calculator truncates to −3 mg. So a hand-converted negative reading can land 1 mg away from what the program prints, and neither is wrong; they round differently.