"Essential Bit Manipulation Techniques in C"

ayushtiic

ツᎪʏᴜꜱʜ ᴋᴜᴍᴀʀ 🇵‌🇦‌🇳‌🇩‌🇪‌🇾

Posted on August 30, 2024

"Essential Bit Manipulation Techniques in C"

Hey folks! This is my first post here on dev.to, and I’m excited to share some insights on Bit Manipulation Techniques. I hope you find this discussion useful and informative.

Here is the List of Bit Manipulation techniques

1. Bitwise OR(|) for Combining Bits:
Bits from multiple sources are combined using the bitwise OR operator (|).

example:

00001100 (12 in binary)
OR
00000111 (7 in binary)
————————————
00001111 (15 in binary)

2. Bitwise AND (&) for Masking and Extracting:
Bitwise AND is used to isolate specific bits from a combined value or check if certain bits are set. This technique can also be used to mask out unwanted bits.
example:

10101111 [175 (0xAF)]
AND
00111100 [60 (0x3C)]
——————————————
00101100 [44 (0x2C)]

3. Bitwise NOT (~)
The Bitwise NOT operation is a unary operation that inverts all bits of its operand. This means that each bit of the number is flipped: 1s become 0s, and 0s become 1s.
example:

00001100 (12 in binary)
~ (Bitwise NOT)
—————————————-
11110011 (-13 as Result in Binary)

3. Bitwise Shift (<<, >>) for Positioning:
Bitwise shift operations are used to move bits to specific positions within a value before combining or extracting them. This is useful for packing multiple values into a single variable.
example:

Operation: 12 << 2

00001100 (12 in binary)
Shift left by 2 positions
———————————————-
00110000 (48 in binary)

Operation: 12 >> 2
00001100 (12 in binary)
Shift right by 2 positions:
———————————————-
00000011 (3 in binary)

4. Bitwise XOR (^):
For each bit position, the XOR operation sets the result bit to 1 if exactly one of the corresponding bits in the operands is 1, but not both.
Example:

00001100 (12 in Binary)
XOR
00000111 (7 in Binary)
—————————————————
00001011 (11 as Result in binary)

5. Bit Masks for Flags:
Bit masks are used to set, clear, or toggle specific bits within a variable. Each bit in the mask represents a different flag or status bit.
example:

Operation: Bitwise OR to set FLAG_A

Initial State: 00001000 (8 in binary)
OR
FLAG_A: 00000001 (1 in binary)
—————————————————-
Result: 00001001 (9 in binary)

Operation: Bitwise AND with NOT of FLAG_B to clear FLAG_B

Initial State: 00001111
AND NOT FLAG_B: 11111101
—————————————————-
Result: 00001101 (13 in binary)

Bitwise XOR to toggle FLAG_C
Initial State: 00001101 (13 in binary)
XOR
FLAG_C 00000100 (4 in binary)
——————————————————-
Result: 00001001 (9 in binary)

6. Packing Bitfields:
Bitfields gives the utility to the User to pack multiple smaller integer values into a single variable. Bitfields are typically used within structs.
example:

Example for Packing Bitfields
Field1: 1010 (4 bits)
Field2: 0101 (4 bits)

Packed Value: 10100101 (165 in decimal)

💖 💪 🙅 🚩

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related