Setting a bit in a binary number means changing a specific bit's value to 1. This is a fundamental operation in programming, especially useful in areas like memory management, data processing, and hardware control.
In this article, we'll explore how to set a bit at a specific position in a binary number using C++. We'll also look into setting multiple bits simultaneously.
How to Set a Bit in C++?
In C++, the OR operator is used to set bits. When you OR a bit with 1, the result is always 1, effectively setting that bit to 1. Here's a truth table for the OR operator:

Setting a Specific Bit in C++
To set a specific bit in a number, we use a bitmask and the bitwise OR operator. The bitmask has a 1 at the position of the bit we want to set and 0s elsewhere.
To create bitmask in C++,
- First identify the bit position (0-based index).
- Use the left shift operator (<<) to move the bit 1 to the desired position.
- The result is a bitmask with a 1 in the specified position and 0s elsewhere.
After that, we can perform the bitwise OR with the binary number to set the desired bit.
Example:
Input:
binary_number: 01100111
bit to set: 5th
Output:
binary_number: 01100111
mask_used: 00100000
In C++, you can achieve this as follows:
// C++ Program to Set a given bit of a binary number
#include <iostream>
using namespace std;
int main()
{
// Binary: 01100111
unsigned int num = 103;
// Setting the 5th bit (0-based index)
unsigned int bit_position = 5;
// Create a mask with only the 5th bit set to 1
unsigned int mask = 1 << bit_position;
// Set the bit using OR
num = num | mask;
// Print the result
cout << "Result: " << num << endl;
return 0;
}
Output
Result: 103
Time Complexity: O(1)
Space Complexity: O(1)
Setting Multiple Bits in C++
You can set multiple bits by combining several bitmasks using the OR operator. Each bitmask will have a 1 in the position of the bit you want to set.
To create bitmask for multiple bits,
- Identify the positions of the bits you want to set.
- Shift 1 to the Left for Each Bit using the left shift operator (<<) for each bit position.
- Use the OR operator (|) to combine the bitmasks.
Example: Setting the 1st, 3rd, and 4th Bits
// C++ Program to Set multiple bits of a binary number
#include <iostream>
using namespace std;
int main()
{
// Binary: 01100111
unsigned int num = 103;
// Create a mask with the 1st, 3rd, and 4th bits set to
// 1
unsigned int mask = (1 << 0) | (1 << 2) | (1 << 3);
// Set the bits using OR
num = num | mask;
// Print the result
cout << "Result: " << num << endl;
return 0;
}
Output
Result: 111
Time Complexity: O(n), where n is the number of bits to be set.
Space Complexity: O(1)
Conclusion
Setting bits in C++ is an essential skill for low-level programming tasks. Using the OR operator in combination with bitmasks allows you to efficiently set one or more bits in a binary number. Mastering this technique is crucial for effective memory and hardware manipulation.