set_bit - 1Fr3aK2/Cub3d GitHub Wiki
Sets or clears a specific bit in an 8-bit variable based on a boolean value.
| Parameter | Type | Description |
|---|---|---|
var |
uint8_t* |
Pointer to the 8-bit variable whose bit will be modified. |
bit |
int |
The index of the bit to modify (0 = least significant bit, 7 = most significant bit). |
value |
bool |
Boolean value indicating whether to set (true) or clear (false) the bit. |
| Return value | Description |
|---|---|
void |
This function does not return a value. |
The set_bit function modifies a single bit in an 8-bit variable. Depending on the value parameter:
- If
valueistrue, the specified bit is set to1. - If
valueisfalse, the specified bit is cleared to0.
Internally, the function uses bitwise operations:
-
*var |= (1 << bit)→ sets the bit. -
*var &= ~(1 << bit)→ clears the bit.
This allows for compact and efficient manipulation of flags or individual bits within a byte.
#include <stdint.h>
#include <stdbool.h>
uint8_t flags = 0b00000000;
// Set the 3rd bit (bit index 2) to 1
set_bit(&flags, 2, true); // flags becomes 0b00000100
// Clear the 3rd bit (bit index 2) back to 0
set_bit(&flags, 2, false); // flags becomes 0b00000000