TExcelTAD
Home › x86-64 Assembly › Bit Manipulation Tricks

Bit Manipulation Tricks

Some problems have surprisingly elegant solutions at the bit level: testing for a power of two, counting set bits, finding the lowest set bit, reversing byte order. Many of them are single instructions on modern x86 CPUs, others are short formulas worth knowing by heart. Compilers use them, cryptography and compression depend on them, and interviewers love them.

Counting bits: popcnt, lzcnt, tzcnt

Instruction Result
popcnt d, s number of 1 bits in s ("population count")
lzcnt d, s number of leading zero bits (from the top)
tzcnt d, s number of trailing zero bits (from the bottom)
bsr d, s index of the highest set bit (older; undefined for 0)
bsf d, s index of the lowest set bit (older; undefined for 0)
nasm · try it yourself
section .text
global _start
_start:
    mov rbx, 0b1011_0000        ; 176

    popcnt rdi, rbx             ; three 1 bits
    call print_uint
    tzcnt rdi, rbx              ; four zeros at the bottom
    call print_uint
    lzcnt rdi, rbx              ; 64 - 8 = 56 zeros at the top
    call print_uint
    bsr rdi, rbx                ; highest set bit: bit 7
    call print_uint

    mov eax, 60
    xor edi, edi
    syscall

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
3
4
56
7

popcnt, lzcnt and tzcnt are newer extensions (supported by practically every x86-64 CPU sold since around 2013). For an input of 0, tzcnt/lzcnt return the operand size (64), whereas bsf/bsr leave the destination undefined.

The x & (x − 1) family

Subtracting 1 flips the lowest set bit and every zero below it. Combining that with and, or and xor gives a set of classic one-liners:

Expression Effect Example (x = 0b10110100)
x & (x - 1) clear the lowest set bit 0b10110000
x & -x isolate the lowest set bit 0b00000100
x | (x - 1) set all bits below the lowest set bit 0b10110111
x & (x - 1) == 0 x is a power of two (or zero) false
nasm · try it yourself
section .text
global _start
_start:
    mov edi, 64
    call is_power_of_two
    mov edi, 96
    call is_power_of_two
    mov edi, 1
    call is_power_of_two

    mov ebx, 0b1011_0100
    mov eax, ebx
    neg eax
    and eax, ebx                ; x & -x: the lowest set bit alone
    mov edi, eax
    call print_uint             ; 4

    mov eax, 60
    xor edi, edi
    syscall

; is_power_of_two(x): print 1 if x is a power of two, else 0
is_power_of_two:
    xor eax, eax
    test rdi, rdi
    jz .print                   ; 0 is not a power of two
    lea rcx, [rdi - 1]
    test rdi, rcx               ; x & (x - 1)
    setz al
.print:
    mov edi, eax
    jmp print_uint

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
1
0
1
4

Counting set bits by hand

Before popcnt existed, Brian Kernighan's trick counted bits by clearing the lowest set bit until nothing is left — the loop runs once per set bit, not once per bit position:

nasm · try it yourself
section .text
global _start
_start:
    mov rax, 0xF0F0_0000_0000_0101  ; 4 + 4 + 1 + 1 = 10 set bits
    xor edi, edi                ; count = 0
.loop:
    test rax, rax
    jz .done
    lea rcx, [rax - 1]
    and rax, rcx                ; clear the lowest set bit
    inc edi
    jmp .loop
.done:
    call print_uint

    mov eax, 60
    xor edi, edi
    syscall

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
10

Bit test instructions

bt, bts, btr and btc test a single bit (copying it into CF) and optionally set, reset or complement it. They are perfect for bitsets: a set of small integers stored as bits of a register or memory block.

nasm · try it yourself
section .bss
seen:   resq 1                  ; a set of the numbers 0..63

section .data
rolls:  dq 4, 17, 4, 33, 17, 8, 4

section .text
global _start
_start:
    xor ecx, ecx
    xor ebx, ebx                ; duplicates found
.next:
    mov rax, [rolls + rcx*8]
    bts [seen], rax             ; CF = old bit, then set it
    adc ebx, 0                  ; count it if it was already set
    inc ecx
    cmp ecx, 7
    jb .next

    mov edi, ebx
    call print_uint             ; duplicates: 4, 17, 4
    popcnt rdi, [seen]
    call print_uint             ; distinct values: 4, 17, 33, 8

    mov eax, 60
    xor edi, edi
    syscall

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
3
4

adc ebx, 0 adds the carry flag, which is a branch-free "if the bit was already set, count one".

Note: bts with a memory operand and a register bit index can address bits far beyond the first qword (the index selects a qword further on), and it is slow. With a register as destination, the index is taken modulo 64.

Swapping byte order: bswap

Network protocols and many file formats store numbers big-endian (most significant byte first). bswap reverses the bytes of a 32- or 64-bit register:

nasm · try it yourself
section .text
global _start
_start:
    mov edi, 0x11223344
    bswap edi                   ; 32-bit: 44 33 22 11
    call print_hex

    mov rdi, 0x0102030405060708
    bswap rdi                   ; 64-bit: all eight bytes reversed
    call print_hex

    mov eax, 60
    xor edi, edi
    syscall

; print_hex: print rdi as 16 hex digits with a 0x prefix and a newline
print_hex:
    sub rsp, 32
    mov word [rsp], '0x'        ; the prefix (NASM stores '0' first, then 'x')
    mov ecx, 16                 ; 16 hex digits
.digit:
    rol rdi, 4                  ; bring the top 4 bits to the bottom
    mov eax, edi
    and eax, 0xF                ; isolate one hex digit (0-15)
    cmp eax, 10
    jb .decimal
    add eax, 'A' - '0' - 10     ; 10-15 -> 'A'-'F'
.decimal:
    add eax, '0'
    mov rdx, 18
    sub rdx, rcx                ; position 2..17 in the buffer
    mov [rsp + rdx], al
    dec ecx
    jnz .digit
    mov byte [rsp + 18], 10     ; newline
    mov eax, 1                  ; write(1, rsp, 19)
    mov edi, 1
    mov rsi, rsp
    mov edx, 19
    syscall
    add rsp, 32
    ret
0x0000000044332211
0x0807060504030201

Branch-free absolute value

An arithmetic right shift by 63 produces 0 for a non-negative number and −1 (all ones) for a negative one. With that mask, (x ^ mask) - mask is x or −x:

nasm · try it yourself
section .text
global _start
_start:
    mov rdi, -1234
    call abs_value
    mov rdi, rax
    call print_int

    mov rdi, 99
    call abs_value
    mov rdi, rax
    call print_int

    mov eax, 60
    xor edi, edi
    syscall

; abs_value(x) -> |x| without a jump
abs_value:
    mov rax, rdi
    sar rdi, 63                 ; mask: 0 or -1
    xor rax, rdi
    sub rax, rdi
    ret

; ---- print_int: print rdi as a signed decimal number and a newline ----
print_int:
    test rdi, rdi
    jns print_uint          ; not negative: print it as it is
    neg rdi                 ; make it positive
    push rdi                ; keep it (write and syscall clobber registers)
    push '-'                ; the minus sign, as a byte on the stack
    mov eax, 1              ; write(1, rsp, 1)
    mov edi, 1
    mov rsi, rsp
    mov edx, 1
    syscall
    pop rdi                 ; drop the '-'
    pop rdi                 ; the positive value again
    jmp print_uint          ; print_uint's ret returns to our caller

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
1234
99

Test yourself

What does x & (x - 1) do?

  1. Doubles x
  2. Clears the lowest set bit of x
  3. Sets the lowest bit
  4. Computes x mod 2

What is popcnt of 0b1110_0001?

  1. 3
  2. 4
  3. 5
  4. 8

What does bswap eax do to 0xAABBCCDD?

  1. 0xDDCCBBAA
  2. 0xBBAADDCC
  3. 0x00000000
  4. 0xAABBCCDD