Shift without undefined behaviour
Make shifts and rotations correct for every shift count. A medium embedded C problem (Undefined behaviour), run and graded in the browser.
medium · Undefined behaviour · undefined-behaviour · bits
In C, shifting a 32-bit value by 32 or more bits is undefined behaviour: on Arm the hardware happens to give 0, on x86 the count is taken modulo 32, and the optimiser may assume it never happens at all. A rotation written as (v << n) | (v >> (32 - n)) is undefined for n == 0, because it shifts by 32.
Write:
shl32(v, n):v << n, but 0 whennis 32 or more,rotl32(v, n): rotate left byn(any value; a rotation by 32 or 33 is the same as by 0 or 1), defined for everyn.
Starter code
uint32_t shl32(uint32_t v, unsigned n) {
return v << n;
}
uint32_t rotl32(uint32_t v, unsigned n) {
return (v << n) | (v >> (32 - n));
}Example tests
Ordinary counts
show(0x80000001u, 1);
show(0x12345678u, 8);Expected output:
v=0x80000001 n=1: shl 0x00000002, rotl 0x00000003
v=0x12345678 n=8: shl 0x34567800, rotl 0x34567812Counts of 0 and 32
show(0xDEADBEEFu, 0);
show(0xDEADBEEFu, 32);Expected output:
v=0xDEADBEEF n=0: shl 0xDEADBEEF, rotl 0xDEADBEEF
v=0xDEADBEEF n=32: shl 0x00000000, rotl 0xDEADBEEFLearn it first
- Undefined behaviour · Undefined, unspecified and implementation-defined behaviour, and why the optimiser makes UB dangerous.