# bit-arrays

#### Accessor words for bit arrays

```\ FORTH BIT Arrays
\ by Bob Dickow ( AKA Budsy) dickow@turbonet.com
\ Feb 26, 2018
\ Notes:
\ endian agnostic, address unit agnostic
\ Vocabulary: 2^ BIT@ BIT! BOOL@ BOOL!
\ BOOL@ and BOOL! are convenience words to avoid converting FALSE to 1
\ 2^ may be handy outside the array access words.
\ Buffers for a bit array should be a minimum of 1 CELL in size

DECIMAL

CELL 8 * CONSTANT AddressUnitBits \ 8 is bits in a byte

\ calulates the power of 2 ( n -- 2^n )
\ (will yield 0 on overflow, by the way)

: 2^   ( n -- n )
2 SWAP DUP 1 > IF
1 DO 2 * LOOP ELSE
NIP DUP 2 = NOT IF 1+
THEN
THEN
;

\ compiling word, creates an array of CELL * 8 powers of 2 for masking use in the array fetch and store words.
\ does: ( nindex -- nvalue  ) \\ nindex is 0, 1, 2 ... giving 2^31, 2^30, 2^29 ... 2^0

: ^2MASKS  ( <name> -- )
CREATE
0 AddressUnitBits 1-  do i 2^ , -1 +loop
does>  swap CELLS + @
;

^2MASKS bmask \ lookup table of powers of 2 for the BIT@ and BOOL@ words

\ factored out, internal use by BIT@,  BOOL@

: _BIT@    ( caddr n -- n )
CELLS        ( caddr n n )
ROT  +       ( n caddr )
@ SWAP       ( nval n )
;

\ given a memory buffer address caddr and index n representing at bit-wise
\ index, return the value of the bit at that index as 1 | 0.

: BIT@   ( caddr n -- n )
_BIT@  ( n )
0= NOT
ABS
;

\ store a value TRUE|FALSE or 1|0, given the value, an address, and a bit-wise index
\ (synonym for BOOL! below)

: BIT!   ( n caddr n -- )
ROT ABS IF [']  OR ELSE ['] XOR  THEN >R \ set masking op
CELLS        ( caddr n n )
SWAP !
;

\ given a memory buffer address caddr and index n representing at bit-wise
\ index, return or store the value of the bit as a TRUE | FALSE values.

: BOOL@   ( caddr n -- flg )
_BIT@  			 ( n )
0= NOT       ( n )
;

\  Synonym for BIT!
\  store a value TRUE|FALSE ( or 1|0 ), given the value n, a base address of the array, and a bit-wise index into it.

: BOOL!   ( n caddr n --  )
BIT!
;

```