Understanding Bitwise Operators in C

01 Jul 2023 Balmiki Mandal 0 C Programming

What are Bitwise Operators?

Bitwise operators are a group of operators used in the C language to manipulate individual bits within a value. These operators can be used to compare, shift, rotate, and set bits of integers. They work on individual bits, so the result of the operation will depend on the bits of the operands.

Types of Bitwise Operators

In C, there are six bitwise operators: bitwise AND (&), bitwise OR (|), bitwise XOR (^), bitwise NOT (~), left shift (<<), and right shift (>>). Each of these operators acts upon the individual bits of its operand and produce a result based on the bits provided.

Bitwise AND (&)

The bitwise AND operator(&) compares two operands bit by bit. If both of the corresponding bits of the operands are 1, the result is 1, otherwise the result is 0. This operator is useful when performing operations on items such as flags and selection masks.

Bitwise OR (|)

The bitwise OR operator (|) also compares two operands bit by bit. If either of the corresponding bits of the operands is 1, the result is 1, otherwise the result is 0. This operator is used to set or clear certain bits in a value.

Bitwise XOR (^)

The bitwise XOR operator (^) is similar to the bitwise OR operator, except that if both of the corresponding bits of the operands are 1, the result is 0, otherwise the result is 1. This operator is useful for checking equality between two values.

Bitwise NOT (~)

The bitwise NOT operator (~) takes one operand and performs a logical NOT on each bit. This is equivalent to flipping all the bits of the operand. This operator is useful for setting or clearing specific bits within a value.

Left Shift (<<)

The left shift operator (<<) shifts the bits of its operand to the left by a specified number of places. Bits shifted out of the most significant bit position are lost; new bits are shifted into the least significant bit position. This operator can be used to multiply a value by a power of 2.

Right Shift (>>)

The right shift operator (>>) does the opposite of the left shift operator. It shifts the bits of its operand to the right by a specified number of places. Bits shifted out of the least significant bit position are lost; new bits are shifted into the most significant bit position. This operator can be used to divide a value by a power of 2.

Conclusion

Bitwise operators are a powerful tool in the C language for manipulating the individual bits of an integer. By combining these operators, complex operations can be performed on binary numbers. This makes them ideal for working with flags, selection masks, and other low-level operations.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.