Quiz Entry - updated: 2026.07.14
What does shr vs sar do and when does each appear?
shr shifts right filling with zeros (unsigned); sar shifts right filling with the sign bit (signed), so each divides by a power of 2 for its respective signedness.
* shr fills vacated bits with 0 (unsigned divide); sar fills with the sign bit (signed divide). *
# Logical: 0xF0 >> 4 = 0x0F (unsigned division by 16)
shr $4, %eax
# Arithmetic: 0xF0 >> 4 = 0xFF (preserves sign for signed division)
sar $4, %eax
| Instruction | Fill bit | Use case |
|---|---|---|
shr |
0 | Unsigned division by power of 2 |
sar |
Sign bit | Signed division by power of 2 |
shl / sal |
0 | Multiplication by power of 2 (both identical) |
Pattern — signed division by 2:
mov %edi, %eax
shr $31, %eax
add %eax, %edi
sar %edi
The shr $31 extracts the sign bit to add a rounding correction before the arithmetic shift. This is how x / 2 compiles for signed integers.
Go deeper:
SAL/SAR/SHL/SHR reference — confirms SHR clears the MSB while SAR replicates the sign bit for signed divide.
Arithmetic shift (Wikipedia) — explains the sign-preserving fill and the round-toward-negative-infinity caveat behind the signed-divide fixup.