C++ Misc - Bit Manipulation
Bit manipulation is a programming technique that involves performing operations on individual bits or groups of bits within a binary representation of a number.
Syntax
Bit manipulation in C++ involves using bitwise operators such as:
&
- bitwise AND|
- bitwise OR^
- bitwise XOR~
- bitwise NOT<<
- left shift>>
- right shift
int a = 0b00101011; // binary literal
int b = 0b11010100;
int c = a & b; // bitwise AND
int d = a | b; // bitwise OR
int e = a ^ b; // bitwise XOR
int f = ~a; // bitwise NOT
int g = a << 2; // left shift
int h = b >> 3; // right shift
Example
Let's say we want to set the third bit of a number to 1.
int number = 0b00001010;
number |= (1 << 2);
This code uses the bitwise OR (|
) operator to set the third bit to 1. The 1 << 2
expression is a left shift that moves the 1 to the third bit position.
Output
number: 0b00001010
number: 0b00001110
Explanation
In the example above, we start with the binary number 0b00001010
which is 10
in decimal. We use the bitwise OR operator (|
) to set the third bit to 1
, resulting in the binary number 0b00001110
, which is 14
in decimal.
Use
Bit manipulation can be used in various applications, such as:
- Setting, clearing, and toggling individual bits in a bitfield.
- Implementing efficient algorithms for tasks such as sorting and searching.
- Optimizing code for size, speed, or other factors.
- Implementing low-level protocols and hardware interfaces.
Important Points
- Bit manipulation involves performing operations on individual bits or groups of bits within a number.
- Bitwise operators such as
&
,|
,^
,~
,<<
, and>>
are used for bit manipulation. - Bit manipulation can be used for various applications such as bitfields, algorithms, optimization, and low-level interfaces.
Summary
Bit manipulation is a useful programming technique that allows us to operate on individual bits or groups of bits within a binary representation of a number. C++ provides bitwise operators such as &
, |
, ^
, ~
, <<
, and >>
for performing bit manipulation. Bit manipulation can be used for various applications such as bitfields, algorithms, optimization, and low-level interfaces.