Bitwise

bit manipulation methods & bitwise operators (AND, OR, XOR, etc) for integer values


Functions


The Bitwise module provides functions for bit-level operations on integer values, including basic boolean operations and bit shifting.

Key Concepts

  • Bitwise boolean operations (AND, OR, XOR, etc.)
  • Bit shifting operations
  • Works with integer values
  • Results are always integers

Basic Usage

Boolean Operations

x: 5    ; binary: 101
y: 3    ; binary: 011

and x y       ; => 1  (001)
or x y        ; => 7  (111)
xor x y       ; => 6  (110)

; complement
not x         ; => -6 (complement of 101)

Advanced Operations

a: 12   ; binary: 1100
b: 9    ; binary: 1001

nand a b      ; => -9
nor a b       ; => -14
xnor a b      ; => -6

Bit Shifting

num: 8   ; binary: 1000

; left shift (multiply by 2^n)
print shl num 2     ; 32 (100000)

; right shift (divide by 2^n)
print shr num 1     ; 4  (100)

Note
Shift operations are equivalent to multiplication or division by powers of 2.

Common Patterns

Checking Individual Bits

value: 42          ; binary: 101010
mask: shl 1 3      ; binary: 001000

if and value mask -> 
    print "Bit 3 is set"

Setting and Clearing Bits

number: 10         ; binary: 1010
pos: 2

; set bit
number: or number shl 1 pos
print ["After setting:" number]    ; After setting: 14 (1110)

; clear bit
number: and number not shl 1 pos
print ["After clearing:" number]   ; After clearing: 10 (1010)