skalibs: the bitarray library interface
Keywords: skalibs c unix bitarray library libstddjb

libstddjb
libskarnet
skalibs
Software
skarnet.org

# The `bitarray` library interface

The following functions are declared in the `skalibs/bitarray.h` header, and implemented in the `libskarnet.a` or `libskarnet.so` library.

## General information

`bitarray` is a set of primitives to operate efficiently on large bitfields.

A bitfield is represented by a pre-allocated block of `unsigned char`; `bitarray` does not care if that block has been BSS-, stack- or heap-allocated. Bitfields that can grow in size should be stored in a stralloc.

Bits in a bitfield of length n are numbered from 0 to n-1.

## Functions

`unsigned int bitarray_div8 (unsigned int n)`
Returns the minimum number of bytes needed to store a field of n bits.

`void bitarray_clearsetn (unsigned char *s, unsigned int start, unsigned int len, int h)`
Sets (if h is nonzero) or clears (if h is zero) len bits in field s, starting at bit start.

`void bitarray_clearn (unsigned char *s, unsigned int start, unsigned int len)`
Clears len bits in field s, starting at bit start.

`void bitarray_setn (unsigned char *s, unsigned int start, unsigned int len)`
Sets len bits in field s, starting at bit start.

`int bitarray_peek (unsigned char const *s, unsigned int n)`
Returns the value of the nth bit in field s.

`void bitarray_poke (unsigned char *s, unsigned int n, int h)`
Sets (if h is nonzero) or clears (if h is zero) the nth bit in field s.

`void bitarray_clear (unsigned char *s, unsigned int n)`
Clears the nth bit in field s.

`void bitarray_set (unsigned char *s, unsigned int n)`
Sets the nth bit in field s.

`int bitarray_testandpoke (unsigned char *s, unsigned int n, int h)`
Sets (if h is nonzero) or clears (if h is zero) the nth bit in field s, and returns the previous value of that bit.

`int bitarray_testandclear (unsigned char *s, unsigned int n)`
Clear the nth bit in field s, and returns the previous value of that bit.

`int bitarray_testandset (unsigned char *s, unsigned int n)`
Sets the nth bit in field s, and returns the previous value of that bit.

`unsigned int bitarray_first (unsigned char const *s, unsigned int len, int h)`
Returns the number of the first set (if h is nonzero) or clear (if h is zero) bit in s, len being the total number of bits. If all bits in s are the negation of h, then len is returned.

`unsigned int bitarray_firstclear (unsigned char const *s, unsigned int len)`
Returns the number of the first clear bit in s, len being the total number of bits. If all bits in s are set, len is returned.

`unsigned int bitarray_firstset (unsigned char const *s, unsigned int len)`
Returns the number of the first set bit in s, len being the total number of bits. If all bits in s are clear, len is returned.