VOOZH about

URL: https://www.geeksforgeeks.org/cpp/setting-bits-in-cpp/

⇱ Setting Bits in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Setting Bits in C++

Last Updated : 10 Jul, 2024

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:

👁 Truth-Table-for-OR-Operation

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:


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,

  1. Identify the positions of the bits you want to set.
  2. Shift 1 to the Left for Each Bit using the left shift operator (<<) for each bit position.
  3. Use the OR operator (|) to combine the bitmasks.

Example: Setting the 1st, 3rd, and 4th Bits


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.

Comment
Article Tags: