Bitwise operations
| AND, OR, XOR, NOT | |
| Shifts | |
| Where you see them |
AND, OR, XOR, NOT
The logic instructions work bit by bit. AND masks bits off, OR masks bits on, XOR flips bits, and XORing a register with itself zeroes it in one instruction:
and eax, 0xFF ; keep the low byte
or eax, 0x80 ; set the top bit of the byte
xor eax, eax ; zero eax, faster than mov
not eax ; flip every bit
Shifts
SHL and SHR shift left and right, SAR shifts right keeping the sign bit, and SAL is SHL by another name. A shift left by n multiplies by 2 to the n, and a shift right divides:
shl eax, 4 ; eax = eax * 16
shr eax, 1 ; eax = eax / 2, unsigned
sar eax, 1 ; eax = eax / 2, signed
Where you see them
Compilers emit shifts for multiplication by constants, XOR for zeroing, and AND for masking in every non-trivial program. Reading them is most of reading a disassembly.
Next: Arrays
Article author: Arthur Isaev