12.13Bit arrays. 4tH 4tH Forth compiler
Reklamë
Reklamë
CHAPTER 12. STANDARD LIBRARIES 181
This program will set the colors in the display buffer of a Sinclair ZX Spectrum. As you can see for yourself, the bitfields behave as you would expect. Only defining them is a little clumsier - nothing a preprocessor can’t fix.
12.13
Bit arrays
A bit array (also known as a bitmap, a bitset, or a bitstring) is an array data structure that compactly stores individual bits (boolean values). Setting it up is a bit awkward, but using it is very simple. First we have to include the libary: include lib/bitarray.4th
Then we have to set up the bit array itself. The minimal size of a bit array is one cell. The total size of a bit array has to be a multiple of cells. Although you can use cells to size the array, the most portable way is to use bits (128 in this example, to be exact):
128 cell-bits / array mybits
Then we have to declare the execution semantics. Note from that moment on, the array is no longer accessable as a cell array. So if you want to initialize the array, the easiest way is to do it before that, otherwise you’ll have to do it bit by bit:
:redo mybits bit-array ;
Or even shorter:
128 cell-bits / array mybits does> bit-array ;
Believe it or not, but that was the hardest part! Manipulating a bit array is dead easy. Bits are numbered zero and up. To set a bit simply issue:
0 mybits bit-on
Resetting or toggling a bit is no rocket science either:
34 mybits bit-off
63 mybits bit-toggle
Of course, you can query the status of a bit. If the bit is set it returns true, otherwise false:
34 mybits bit?
Because of their compactness, bit arrays have a number of applications in areas where space or efficiency is at a premium. Most commonly, they are used to represent a simple group of boolean flags or an ordered sequence of boolean values. However, bit arrays can also be used for the allocation of memory pages, inodes, disk sectors, etc. In such cases, the term ”bitmap” may be used
11
.
11
Not to be confused with raster images, which is something entirely different.
Shkarko
Reklamë