![]() |
In bit manipulation, setting a bit, clearing a bit, and toggling a single bit are basic operations. We can easily carry out these operations using the bitwise operators in C++. In this article, we will see how to set, clear, and toggle operations on the Kth bit. Example Input: N = 15, K = 0 Explanation: 15 is represented as 1111 in binary and has its first bit 1. Setting it will result in 1111 (15 in decimal). Clearing it will result in 1110 (14 in decimal). Toggling it will result in 1110 (14 in decimal). Setting a BitSetting a bit means that if the given K-th bit is 0, then we set it to 1 and if it is 1 then simply ignore it. By performing bitwise OR (‘ | ‘) of a set bit with any bit gives a set bit only, i.e. 0 | 1 = 1 and 1 | 1 = 1. So we can use bitwise OR to set a bit. Formula: number |= 1 << bit_position
Clearing a BitClearing a bit means that if the K-th bit is 1, then we clear it to 0, and if it is 0 then simply ignore it. By performing bitwise AND (‘&’) of a reset bit with any bit gives a reset bit, i.e. 0 & 0 = 0 and 1 & 0 = 0. So, we can use the bitwise AND (&) operator along with the bitwise NOT ( Formula: number &= ~(1 << bit_position);
Toggling a BitToggling a bit means that if the K-th bit is 1, then we change it to 0 and if it is 0 then change it to 1. By performing XOR (‘^’) of set and unset gives a set bit and XOR of a set and set bit or unset and unset bits gives an unset bit, i.e. 0 ^ 1 = 1 and 1 ^ 1 = 0. So we can use XOR to toggle a bit. Formula: number ^= 1 << bit_position;
C++ Program to Set, Clear and Toggle a BitThe below example demonstrates how to perform set, clear and toggle operations on a single bit. C++
Output
15 with 0-th bit Set: 15 15 with 0-th bit Cleared: 14 15 with 0-th bit Toggled: 14 |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |