LOGBOOK

HELP

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.

0xF0 shifted right by 4: shr fills with zeros giving 0x0F (unsigned divide), sar fills with the sign bit giving 0xFF (signed divide preserving -1)

* 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:

From Quiz: REVE1 / Assembly Patterns & GDB | Updated: Jul 14, 2026