Bit Shifts, Significant Bits, and Extracting Bytes (Intel Syntax)
Concepts
- Bytes in a 64-bit register:
rdi
= 64 bits = 8 bytes.- 1st least significant byte (LSB) → bits 0–7
- 2nd byte → bits 8–15
- 3rd byte → bits 16–23
- 4th byte → bits 24–31
- 5th byte → bits 32–39
On x86-64 in Intel syntax, the sh
family of instructions is:
shl reg, imm
→ shift left (multiply by 2^imm)shr reg, imm
→ shift right logical (divide unsigned by 2^imm)sar reg, imm
→ shift right arithmetic (divide signed by 2^imm, preserving sign bit)- To isolate a byte using only shifts:
- Shift right to bring target byte into the lowest 8 bits.
- Shift left to clear higher bits and leave only that byte.
Example
- Extract the 5th least significant byte of
rdi
(bits 32–39). - Place result in
rax
. - Allowed instructions:
mov
,shr
,shl
.
.intel_syntax noprefix
.global _start
.section .text
_start:
mov rax, rdi ; copy input
shr rax, 32 ; shift right 32 bits → 5th byte now in lowest 8 bits
shl rax, 56 ; clear out everything except that byte
shr rax, 56 ; move it back down into lowest 8 bits
; now rax holds only the 5th byte
or
.intel_syntax noprefix
.global _start
_start:
shl rdi, 24
shr rdi, 56
mov rax, rdi
shr rax, 32
→ moves byte 5 down into position 0.shl rax, 56
→ clears all bits except that byte (forces others out).shr rax, 56
→ moves it back down to the LSB for a clean result.
Final: rax
contains the 5th least significant byte of rdi
.
Resources
Resource | Description |
---|---|
1.2 - Bitwise Logic in x86 (Intel Syntax) | Next note |