7. Bitwise Instructions
7. Bitwise Instructions
Bitwise instructions operate on individual bits within numbers. They’re incredibly fast and are the foundation for many low-level operations, from graphics to cryptography to hardware control.
What are Bitwise Operations?
Instead of treating numbers as values, bitwise operations work on the binary representation of numbers, manipulating each bit individually.
Example:
Number: 170 = 10101010 (binary)
Number: 85 = 01010101 (binary)
The Basic Bitwise Instructions
1. AND - Logical AND
Sets bits to 1 only if both corresponding bits are 1.
1
2
3
mov rax, 0b1100 ; 12 decimal
mov rbx, 0b1010 ; 10 decimal
and rax, rbx ; RAX = 0b1000 (8 decimal)
Its common uses are -
- Masking bits: Clear specific bits while preserving others
- Check if bits are set: Test multiple bits at once
1
2
3
4
5
6
; Clear lower 4 bits (mask with 0xF0)
mov al, 0xAB ; 10101011
and al, 0xF0 ; 11110000 - Result: 10100000 (0xA0)
; Check if number is even (bit 0 = 0)
test al, 1 ; ZF=1 if even, ZF=0 if odd
2. OR - Logical OR
Sets bits to 1 if either corresponding bit is 1.
1
2
3
mov rax, 0b1100 ; 12 decimal
mov rbx, 0b1010 ; 10 decimal
or rax, rbx ; RAX = 0b1110 (14 decimal)
Its common uses are -
- Set specific bits: Force certain bits to 1
- Combine bit fields
1
2
3
4
5
6
7
8
; Set bit 3 (make it 1)
mov al, 0x81 ; 10000001
or al, 0x08 ; 00001000 - Result: 10001001 (0x89)
; Combine two 4-bit values
mov al, 0xA0 ; 10100000 (high nibble)
mov bl, 0x07 ; 00000111 (low nibble)
or al, bl ; Result: 10100111 (0xA7)
3. XOR - Exclusive OR
Sets bits to 1 only if corresponding bits are different.
1
2
3
mov rax, 0b1100 ; 12 decimal
mov rbx, 0b1010 ; 10 decimal
xor rax, rbx ; RAX = 0b0110 (6 decimal)
Its common uses are -
- Toggle bits: Flip specific bits
- Zero a register efficiently
- Encryption: Simple cipher operations
1
2
3
4
5
6
7
8
9
10
11
; Toggle bits 2 and 3
mov al, 0b00110011
xor al, 0b00001100 ; Result: 0b00111111
; Zero a register (faster than mov)
xor rax, rax ; RAX = 0
; Simple encryption/decryption
mov al, 'A' ; Character to encrypt
xor al, 0x55 ; Encrypt with key
xor al, 0x55 ; Decrypt (same operation!)
4. NOT - Logical NOT
Inverts all bits (1’s complement).
1
2
mov rax, 0b1100 ; 12 decimal
not rax ; RAX = 0xFFFFFFFFFFFFFFF3 (in 64-bit)
Note: NOT is different from NEG (two’s complement negation).
5. TEST - AND Without Storage
Performs AND operation but only sets flags, doesn’t store result.
1
2
3
mov rax, 0b1010
test rax, 0b1000 ; Check if bit 3 is set
; ZF=0 (bit is set), ZF=1 (bit is not set)
This post is licensed under CC BY 4.0 by the author.