Skip to content

set_bit

Mallikarjunarao Kosuri edited this page Jul 14, 2024 · 1 revision

set_bit Function

The set_bit function sets the bit at position p of the byte x to 1.

uint8_t set_bit(uint8_t x, uint8_t p)
{
    return (x | (1 << p));
}

Explanation

  1. Bit Shifting: The expression (1 << p) shifts the number 1 to the left by p positions. This creates a mask with a 1 at the p-th position and 0s elsewhere.

  2. Bitwise OR: The bitwise OR operator | combines the original number x with the mask. This sets the bit at position p to 1 while leaving all other bits unchanged.

Example

Let's take an example where x = 5 (binary 00000101) and p = 2.

Step-by-Step Process

  1. Initial Value:

    • x = 00000101 (binary)
    • p = 2
  2. Create the Mask:

    • 1 << p shifts 1 to the left by 2 positions.
    • 1 << 2 becomes 00000100 (binary).
  3. Bitwise OR Operation:

    • Original x: 00000101
    • Mask: 00000100
    • Result of x | (1 << p): 00000101 | 00000100

Bitwise OR Operation

Bit Position 7 6 5 4 3 2 1 0
x 0 0 0 0 0 1 0 1
1 << p 0 0 0 0 0 1 0 0
Result 0 0 0 0 0 1 0 1

The 2-th bit of x is set to 1, resulting in 00000101 which is 5 in decimal.

Another example

x = 00000101  (binary for 5)
p = 2

Step 1: Shift 1 left by 2 positions
1 << 2 = 00000100

Step 2: Perform bitwise OR with x
x       = 00000101
1 << p  = 00000100
----------------
Result  = 00000101

Summary

The set_bit function works by creating a mask with a 1 at the desired bit position and then using the bitwise OR operation to set that bit in the original number.

In our example, setting the 2-th bit of 5 doesn't change the value because the bit was already 1. If it was 0, it would have been set to 1.

Clone this wiki locally