Bitwise Operations

Bitwise operations library contains a set of macro functions to do common bit manipulation operations. They are used by the rest of the library and can be used everywhere else. As the macro-functions have no type, they are compatible with any data type.

Bit index is used to specify the bit in the binary number. Indexes are counted from zero, where zero represents the least significant bit (LSB). For example, an 8-bit number has 8 bits with indexes from 0 to 7 and a 16-bit number has 16 bits with indexes from 0 to 15.

Functions

Bit index to bit mask converting. Parameters:

• bit - Bit index.
• bit_set(value, bit)

Sets a specified bit in the variable. Parameters:

• value - Variable.
• bit - Bit index.
• bit_clear(value, bit)

Clears a specified bit in the variable. Parameters:

• value - Variable.
• bit - Bit index.
• bit_set_to(value, bit, state)

Set a specified bit in the variable to desired state. Parameters:

• value - Variable.
• bit - Bit index.
• state - State (true or false).
• bit_invert(value, bit)

Inverts a specified bit in the variable. Parameters:

• value - Variable.
• bit - Bit index.
• bit_is_set(value, bit)

Checks whether a specified bit in the variable is set or not. Parameters:

• value - Variable.
• bit - Bit index.
• Returns boolean value true when bit is set and false when bit is cleared.
• bit_is_clear(value, bit)

Checks whether a specified bit in the variable is cleared or not. Parameters:

• value - Variable.
• bit - Bit index.
• Returns boolean value true when bit is cleared and false when bit is set.

Example

Setting up a third bit in the 8-bit variable b and inverting of the last one.

```#include <homelab/bit.h>

int main(void)
{
unsigned char b = 0x00;

bit_set(b, 2);
bit_invert(b, 7);
}```

Source

The following is a shortened version of the bitwise operations library source code.

```//
// Functions for handling bits.
//
#define bit_set(value, bit)      value |= bit_mask(bit)
#define bit_clear(value, bit)    value &= ~bit_mask(bit)
#define bit_invert(value, bit)   value ^= bit_mask(bit)
#define bit_is_set(value, bit)   ((value) & (bit_mask(bit)))
#define bit_is_clear(value, bit) (!((value) & (bit_mask(bit))))
#define bit_set_to(v, b, x) v = ((x) ? (v | bit_mask(b)) : (v & ~bit_mask(b)))

//
// Functions for handling bit masks.
//