Bitwise operations

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.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does xor eax, eax do?

    Answer

    It zeroes eax

    XOR of equal values is zero, and the instruction is shorter than a load of 0.

  2. Which operation keeps only the low four bits of a value?

    Answer

    AND with 0xF

    A mask of 0xF has ones in the low nibble, and AND keeps only the bits where the mask has ones.

  3. What does shl eax, 4 do?

    Answer

    It multiplies by 16

    A left shift by four multiplies by 2 to the fourth power, which is 16.

  4. Which shift keeps the sign bit when it shifts right?

    Answer

    SAR

    SAR copies the top bit into the vacated positions, so negative numbers stay negative.

  5. What is SAL?

    Answer

    A different name for SHL

    The two mnemonics encode the same shift-left instruction.

  6. What does not eax do?

    Answer

    It flips every bit of eax

    NOT is the bitwise complement; NEG is the arithmetic negation.

  7. What does this program print? default rel section .data msg db "A", 10 section .text global _start _start: mov al, [msg] or al, 0x20 mov [msg], al mov rax, 1 mov rdi, 1 mov rsi, msg mov rdx, 2 syscall mov rax, 60 xor rdi, rdi syscall

    Answer

    a

    Bit 5 of an ASCII letter is the case bit, and OR with 0x20 sets it, turning A into a.

  8. What exit status does this program return? section .text global _start _start: mov rax, 3 shl rax, 3 mov rdi, rax mov rax, 60 syscall

    Answer

    24

    3 shifted left three times is 3 times 8, which is 24.

  9. What is the result of and eax, 0?

    Answer

    eax becomes zero

    AND with a zero mask clears every bit.

  10. Why do compilers use shifts instead of MUL for powers of two?

    Answer

    Shifts are shorter and faster

    A shift needs one instruction and no multiply unit, and by a constant it is exact.

The snippets on this page are fragments, not whole programs: they show the logic instructions and the shifts. They were assembled with NASM 3.01 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev