Bitfield

A tiny little bit of code that allows for efficient storage and access to large amounts of boolean data.

Author
Stephen Brennan
Date
Created Sunday, 3 August 2014
Copyright
Copyright (c) 2013-2016, Stephen Brennan. Released under the Revised BSD License. See the LICENSE.txt file for details.

Defines

BIT_PER_CHAR

Number of bits in a char type. Shouldn’t really change...

SMB_BITFIELD_SIZE(num_bools)

Get the number amount of space eneded for a bitfield of the specified amount of booleans.

If you want to allocate a buffer on the stack, you need this macro.

Return
The number of bytes
Parameters
  • num_bools: The number of booleans.

Functions

void bf_init(unsigned char * data, int num_bools)

Initialize the memory where a bitfield is contained to all 0’s.

This is public so people can use the function to allocate their own bitfields on function stacks instead of via the heap. No errors are defined for this function.

Parameters
  • data: A pointer to the bitfield.
  • num_bools: The size of the bitfield, in number of bools (aka bits, not bytes).

unsigned char* bf_create(int num_bools)

Allocate a bitfield capable of holding the given number of bools.

This will be allocated in dynamic memory, and a pointer will be returned. The bf_init function is available for creating bitfields in arbitrary locations.

Return
A pointer to the bitfield.
Parameters
  • num_bools: The number of bools to fit in the bit field.

void bf_delete(unsigned char * data, int num_bools)

Delete the bitfield pointed to. Only do this if you created the bitfield via bf_create().

Parameters
  • data: A pointer to the bitfield.
  • num_bools: The number of bools contained in the bitfield.

int bf_check(unsigned char * data, int index)

Check whether the given bit is set.

Parameters
  • data: A pointer to the bitfield.
  • index: The index of the bit to Check
Return Value
  • 0: if the bit is not set.
  • Nonzero: if the bit is set.

void bf_set(unsigned char * data, int index)

Set a bit.

Parameters
  • data: A pointer to the bitfield
  • index: The index of the bit to set.

void bf_clear(unsigned char * data, int index)

Clear a bit.

Parameters
  • data: A pointer to the bitfield.
  • index: The index of the bit to clear.

void bf_flip(unsigned char * data, int index)

Clear a bit.

Parameters
  • data: A pointer to the bitfield.
  • index: The index of the bit to flip.