set_bit - 1Fr3aK2/Cub3d GitHub Wiki

📝 set_bit

Sets or clears a specific bit in an 8-bit variable based on a boolean value.

⚙️ Parameters

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.

🔁 Returns

Return value Description
void This function does not return a value.

📖 Description

The set_bit function modifies a single bit in an 8-bit variable. Depending on the value parameter:

  • If value is true, the specified bit is set to 1.
  • If value is false, the specified bit is cleared to 0.

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.

💡 Example Usage

#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
⚠️ **GitHub.com Fallback** ⚠️