Additional bitwise arithmetic
Factor handbook » The language » Numbers » Arithmetic » Bitwise arithmetic

Prev:bit? ( x n -- ? )
Next:Integer virtual sequences

The math.bitwise vocabulary provides bitwise arithmetic words extending Bitwise arithmetic. They are useful for efficiency, low-level programming, and interfacing with C libraries.

Setting and clearing bits:
set-bit ( x n -- y )
clear-bit ( x n -- y )

Testing if bits are set:
bit? ( x n -- ? )

Extracting bits from an integer:
bit-range ( x high low -- y )
bits ( m n -- m' )

Toggling a bit:
toggle-bit ( m n -- m' )

Operations with bitmasks:
mask ( x n -- y )
unmask ( x n -- y )
mask? ( x n -- ? )
unmask? ( x n -- ? )

Generating an integer with n set bits:
on-bits ( m -- n )

Counting the number of set bits:
bit-count ( obj -- n )

Testing the parity of an object:
even-parity? ( obj -- ? )
odd-parity? ( obj -- ? )

More efficient modding by powers of two:
wrap ( m n -- m' )

Bit-rolling:
bitroll ( x s w -- y )
bitroll-32 ( m s -- n )
bitroll-64 ( m s -- n )

32-bit arithmetic:
w+ ( x y -- z )
w- ( x y -- z )
w* ( x y -- z )

64-bit arithmetic:
W+ ( x y -- z )
W- ( x y -- z )
W* ( x y -- z )

Words for taking larger integers apart into smaller integers:
d>w/w ( d -- w1 w2 )
w>h/h ( w -- h1 h2 )
h>b/b ( h -- b1 b2 )

Converting a number to the nearest even/odd/signed:
>even ( m -- n )
>odd ( m -- n )
>signed ( x n -- y )

Bitfields:
Constructing bit fields