-
Notifications
You must be signed in to change notification settings - Fork 0
set_bit
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));
}-
Bit Shifting: The expression
(1 << p)shifts the number1to the left byppositions. This creates a mask with a1at thep-th position and0s elsewhere. -
Bitwise OR: The bitwise OR operator
|combines the original numberxwith the mask. This sets the bit at positionpto1while leaving all other bits unchanged.
Let's take an example where x = 5 (binary 00000101) and p = 2.
-
Initial Value:
-
x = 00000101(binary) p = 2
-
-
Create the Mask:
-
1 << pshifts1to the left by2positions. -
1 << 2becomes00000100(binary).
-
-
Bitwise OR Operation:
- Original
x:00000101 - Mask:
00000100 - Result of
x | (1 << p):00000101 | 00000100
- Original
| 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.
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
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.