Bits manipulation (Important tactics) in C++

C++Server Side ProgrammingProgramming

Let’s first recall the about bits and the bitwise operator is short.

Bit is a binary digit. It is the smallest unit of data that is understandable by the computer. In can have only one of the two values 0 (denotes OFF) and 1 (denotes ON).

Bitwise operators are the operators that work a bit level in the program.

These operators are used to manipulate bits in the program.

In C, we have 6 bitwise operators −

  • Bitwise AND (&)

  • Bitwise OR (OR)

  • Bitwise XOR (XOR)

  • Bitwise left Shift (<<)/p>

  • Bitwise right Shift (>>)

  • Bitwise not (~)

https://www.tutorialspoint.com/cprogramming/c_bitwise_operators.htm

Now, let’s learn some important tactics i.e. things that can be helpful if you work with bits.

Swap two number (using bitwise XOR)

We can swap two values using the bitwise XOR operator. The implementation is −

Example

 Live Demo

#include <stdio.h>
int main(){
   int x = 41;
   int y = 90;
   printf("Values before swapping! 
");    printf("x = %d \t", x);    printf("y = %d
", y);    x = x ^ y;    y = y ^ x;    x = x ^ y;    printf("Values after swapping!
");    printf("x = %d \t", x);    printf("y = %d
", y);    return 0; }

Output

Values before swapping!
x = 41 y = 90
Values before swapping!
x = 90 y = 41

Efficient way to find MSB (most significant bit)

For any integer value, we can find the most significant bit is an effective way. This is done using or operator along with a bitwise shift operator. This method can find the MSB in o(1) time complexity.

The size of the integer should be predefined to create the program.

Example

Program to find MSB of 32-bit integer −

 Live Demo

#include <stdio.h>
int findMSB(int x){
   x |= x>>1;
   x |= x>>2;
   x |= x>>4;
   x |= x>>8;
   x |= x>>16;
   x = x+1;
   return(x >> 1);
}
int main(){
   int x = 49;
   printf("The number is %d
", x);    int msb = findMSB(x);    printf("MSB of the number is %d
", msb); }

Output

The number is 49
MSB of the number is 32

Directly calculate the XOR of all numbers from 1 to n.

If we observe the XOR of 0 to n carefully we can derive a general pattern. Which is illustrated here −

Example

 Live Demo

#include <stdio.h>
// Direct XOR of all numbers from 1 to n
int findXORuptoN(int n){
   switch( n%4){
      case 0: return n;
      case 1: return 1;
      break;
      case 2: return n+1;
      break;
      case 3: return 0;
      break;
      default: break;
   }
}
int main(){
   int n = 9870;
   int xorupton = findXORuptoN(n);
   printf("XOR of all number up to %d is %d
", n, xorupton); }

Output

XOR of all number up to 9870 is 9871

Directly calculating the total number of combinations with a number smaller than or equal to with a number whose sum and XOR are equal.

Using the bitwise shifting operators, we can easily do the work and it will require less time.

Example

 Live Demo

#include <stdio.h>
int countValues(int n){
   int unset=0;
   while (n){
      if ((n & 1) == 0)
         unset++;
      n=n>>1;
   }
   return (1<<unset);
}
int main(){
   int n = 32;
   printf("%d", countValues(n));
}

Output

32

Finding the number of leading and trailing 0’s in an integer

There are inbuilt methods to find the number of leading and trailing zeroes of an integer, thanks to bit manipulation.

* It is a GCC inbuilt function

Example

 Live Demo

#include <stdio.h>
int main(){
   int n = 32;
   printf("The integer value is %d
", n);    printf("Number of leading zeros is %d
", __builtin_clz(n));    printf("Number of trailing zeros is %d
",__builtin_clz(n)); }

Output

The integer value is 32
Number of leading zeros is 26
Number of trailing zeros is 26

Check if a number is a power of two?

To check, if a number is a power of 2, is made easy using a bitwise operator.

Example

 Live Demo

#include <stdio.h>
int isPowerof2(int n){
   return n && (!(n&(n-1)));
}
int main(){
   int n = 22;
   if(isPowerof2(n))
      printf("%d is a power of 2", n);
   else
      printf("%d is not a power of 2", n);
}

Output

22 is not a power of 2

Find XOR of all subsets of a set

This can be done using the fact that if there are more than 1 element the XOR of all subsets is always 0 and the number otherwise.

Example

 Live Demo

#include <stdio.h>
int findsubsetXOR (int set[], int size){
   if (size == 1){
      return set[size - 1];
   }
   else
      return 0;
}
int main (){
   int set[] = { 45, 12 };
   int size = sizeof (set) / sizeof (set[0]);
   printf ("The XOR of all subsets of set of size %d is %d
", size,    findsubsetXOR (set, size));    int set2[] = { 65 };    size = sizeof (set2) / sizeof (set2[0]);    printf ("The XOR of all subsets of set of size %d is %d
", size,    findsubsetXOR (set2, size)); }

Output

The XOR of all subsets of set of size 2 is 0
The XOR of all subsets of set of size 1 is 65

To convert the given binary number of integer

auto keyword in C is employed to do the task.

Example

 Live Demo

#include <stdio.h>
int main (){
   auto integer = 0b0110110;
   printf("The integer conversion of binary number '0110110' is %d", integer);
}

Output

The integer conversion of binary number '0110110' is 54

Flipping all bits of a number

We can flip all the bits of a number by subtracting it from a number whose all bits are set.

Number = 0110100
The number will all bits set = 1111111
Subtraction -> 1111111 - 0110100 = 1001011 (number with flipped bits)

Example

 Live Demo

#include <stdio.h>
int main (){
   int number = 23;
   int n = number;
   n |= n>>1;
   n |= n>>2;
   n |= n>>4;
   n |= n>>8;
   n |= n>>16;
   printf("The number is %d
", number);    printf("Number with reversed bits %d
", n-number); }

Output

The number is 23
Number with reversed bits 8

Check if bits have alternate pattern

Using the bitwise XOR operation, we can find if the bits of a number are in alternate patterns or not. The below code shows how to −

Example

 Live Demo

#include <stdio.h>
int checkbitpattern(int n){
   int result = n^(n>>1);
   if(((n+1)&n) == 0)
      return 1;
   else
      return 0;
}
int main (){
   int number = 4;
   if(checkbitpattern == 1){
      printf("Bits of %d are in alternate pattern", number);
   }
   else
      printf("Bits of %d are not in alternate pattern", number);
}

Output

Bits of 4 are not in alternate pattern
raja
Updated on 05-Aug-2020 07:47:30

Advertisements