The Wayback Machine - https://web.archive.org/web/20240901094741/https://www.geeksforgeeks.org/complete-reference-for-bitwise-operators-in-programming-coding/
Open In App

Complete Reference for Bitwise Operators in Programming/Coding

Last Updated : 28 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Topics:
Solve Problem
Easy
49.22%
29.2K

There exists no programming language that doesn’t use Bit Manipulations. Bit manipulation is all about these bitwise operations. They improve the efficiency of programs by being primitive, fast actions. There are different bitwise operations used in bit manipulation. These Bitwise Operators operate on the individual bits of the bit patterns. Bit operations are fast and can be used in optimizing time complexity.

Some common bit operators are:

Bitwise Operator Truth Table

Bitwise Operator Truth Table

1. Bitwise AND Operator (&)

The bitwise AND operator is denoted using a single ampersand symbol, i.e. &. The & operator takes two equal-length bit patterns as parameters. The two-bit integers are compared. If the bits in the compared positions of the bit patterns are 1, then the resulting bit is 1. If not, it is 0.

Truth table of AND operator

Truth table of AND operator

Example: 

Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise and of both X & y

Bitwise and of 7 & 4

Bitwise ANDof (7 & 4)

Implementation of AND operator:

C++




#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
    int a = 7, b = 4;
    int result = a & b;
    cout << result << endl;
 
    return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static void main (String[] args) {
        int a = 7, b = 4;
          int result = a & b;
          System.out.println(result);
    }
}
 
// This code is contributed by lokeshmvs21.


Python3




a = 7
b = 4
result = a & b
print(result)
# This code is contributed by akashish__


C#




using System;
 
public class GFG{
 
    static public void Main (){
      int a = 7, b = 4;
      int result = a & b;
      Console.WriteLine(result);
    }
}
 
// This code is contributed by akashish__


Javascript




let a = 7, b = 4;
let result = a & b;
console.log(result);
// This code is contributed by akashish__


Output

4







Time Complexity: O(1) 
Auxiliary Space: O(1)

2. ​Bitwise OR Operator (|)

The | Operator takes two equivalent length bit designs as boundaries; if the two bits in the looked-at position are 0, the next bit is zero. If not, it is 1.

BItwiseORoperatortruthtable-300x216-(2)

Example: 

Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise OR of both X, y

Bitwise OR of (7 | 4)

Explanation: On the basis of truth table of bitwise OR operator we can conclude that the result of 

1 | 1  = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0

We used the similar concept of bitwise operator that are show in the image.

Implementation of OR operator:

C++




#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
    int a = 12, b = 25;
    int result = a | b;
    cout << result;
 
    return 0;
}


Java




import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        int a = 12, b = 25;
        int result = a | b;
        System.out.println(result);
    }
}


Python3




a = 12
b = 25
result = a | b
print(result)
 
# This code is contributed by garg28harsh.


C#




using System;
 
public class GFG{
 
    static public void Main (){
        int a = 12, b = 25;
        int result = a | b;
        Console.WriteLine(result);
    }
}
// This code is contributed by akashish__


Javascript




    let a = 12, b = 25;
    let result = a | b;
    document.write(result);
       
// This code is contributed by garg28harsh.


Output

29






Time Complexity: O(1) 
Auxiliary Space: O(1)

3. ​Bitwise XOR Operator (^)

The ^ operator (also known as the XOR operator) stands for Exclusive Or. Here, if bits in the compared position do not match their resulting bit is 1. i.e, The result of the bitwise XOR operator is 1 if the corresponding bits of two operands are opposite, otherwise 0.

BItwiseXORoperatortruthtable-300x216-(1)

Example: 

Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise and of both X & y

Bitwise OR of (7 ^ 4)

Explanation: On the basis of truth table of bitwise XOR operator we can conclude that the result of 

1 ^ 1  = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0

We used the similar concept of bitwise operator that are show in the image.

Implementation of XOR operator:

C++




#include <iostream>
using namespace std;
 
int main()
{
 
    int a = 12, b = 25;
    cout << (a ^ b);
    return 0;
}


Java




import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        int a = 12, b = 25;
        int result = a ^ b;
        System.out.println(result);
    }
}
 
// This code is contributed by garg28harsh.


Python3




a = 12
b = 25
result = a ^ b
print(result)
 
# This code is contributed by garg28harsh.


C#




// C# Code
 
using System;
 
public class GFG {
 
    static public void Main()
    {
 
        // Code
        int a = 12, b = 25;
        int result = a ^ b;
        Console.WriteLine(result);
    }
}
 
// This code is contributed by lokesh


Javascript




let a = 12;
let b = 25;
console.log((a ^ b));
// This code is contributed by akashish__


Output

21






Time Complexity: O(1) 
Auxiliary Space: O(1)

4. ​Bitwise NOT Operator (!~)

All the above three bitwise operators are binary operators (i.e, requiring two operands in order to operate). Unlike other bitwise operators, this one requires only one operand to operate.

The bitwise Not Operator takes a single value and returns its one’s complement. The one’s complement of a binary number is obtained by toggling all bits in it, i.e, transforming the 0 bit to 1 and the 1 bit to 0.

Truth Table of Bitwise Operator NOT

Truth Table of Bitwise Operator NOT

Example: 

Take two bit values X and Y, where X = 5= (101)2 . Take Bitwise NOT of X.

Explanation: On the basis of truth table of bitwise NOT operator we can conclude that the result of 

~1  = 0
~0 = 1

We used the similar concept of bitwise operator that are show in the image.

Implementation of NOT operator:

C++




#include <iostream>
using namespace std;
 
int main()
{
 
    int a = 0;
    cout << "Value of a without using NOT operator: " << a;
    cout << "\nInverting using NOT operator (with sign bit): " << (~a);
    cout << "\nInverting using NOT operator (without sign bit): " << (!a);
 
    return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
  public static void main(String[] args)
  {
    int a = 0;
    System.out.println(
      "Value of a without using NOT operator: " + a);
    System.out.println(
      "Inverting using NOT operator (with sign bit): "
      + (~a));
    if (a != 1)
      System.out.println(
      "Inverting using NOT operator (without sign bit): 1");
    else
      System.out.println(
      "Inverting using NOT operator (without sign bit): 0");
  }
}
 
// This code is contributed by lokesh.


Python3




a = 0
print("Value of a without using NOT operator: " , a)
print("Inverting using NOT operator (with sign bit): " , (~a))
print("Inverting using NOT operator (without sign bit): " , int(not(a)))
#  This code is contributed by akashish__


C#




using System;
 
public class GFG {
 
  static public void Main()
  {
 
    int a = 0;
    Console.WriteLine(
      "Value of a without using NOT operator: " + a);
    Console.WriteLine(
      "Inverting using NOT operator (with sign bit): "
      + (~a));
    if (a != 1)
      Console.WriteLine(
      "Inverting using NOT operator (without sign bit): 1");
    else
      Console.WriteLine(
      "Inverting using NOT operator (without sign bit): 0");
  }
}
 
// This code is contributed by akashish__


Javascript




let a =0;
document.write("Value of a without using NOT operator: " + a);
document.write( "Inverting using NOT operator (with sign bit): " + (~a));
if(!a)
document.write( "Inverting using NOT operator (without sign bit): 1" );
else
document.write( "Inverting using NOT operator (without sign bit): 0" );


Output

Value of a without using NOT operator: 0
Inverting using NOT operator (with sign bit): -1
Inverting using NOT operator (without sign bit): 1






Time Complexity: O(1) 
Auxiliary Space: O(1)

5. Left-Shift (<<)

The left shift operator is denoted by the double left arrow key (<<). The general syntax for left shift is shift-expression << k. The left-shift operator causes the bits in shift expression to be shifted to the left by the number of positions specified by k. The bit positions that the shift operation has vacated are zero-filled. 

Note: Every time we shift a number towards the left by 1 bit it multiply that number by 2.

Logical left Shift

Logical left Shift

Example:

Input: Left shift of 5 by 1.
Binary representation of 5 = 00101 and Left shift of 001012 by 1 (i.e, 00101 << 1)
 

Left shift of 5 by 1

Output: 10
Explanation: All bit of 5 will be shifted by 1 to left side and this result in 010102, Which is equivalent to 10

Input: Left shift of 5 by 2.
Binary representation of 5 = 00101 and Left shift of 001012 by 1 (i.e, 00101 << 2)

Left shift of 5 by 2

Output: 20
Explanation: All bit of 5 will be shifted by 1 to left side and this result in 101002, Which is equivalent to 20

Input: Left shift of 5 by 3.
Binary representation of 5 = 00101 and Left shift of 001012 by 1 (i.e, 00101 << 3)

Left shift of 5 by 3

Output: 40
Explanation: All bit of 5 will be shifted by 1 to left side and this result in 010002, Which is equivalent to 40

Implementation of Left shift operator:

C++




#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    unsigned int num1 = 1024;
 
    bitset<32> bt1(num1);
    cout << bt1 << endl;
 
    unsigned int num2 = num1 << 1;
    bitset<32> bt2(num2);
    cout << bt2 << endl;
 
    unsigned int num3 = num1 << 2;
    bitset<16> bitset13{ num3 };
    cout << bitset13 << endl;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
  public static void main(String[] args)
  {
    int num1 = 1024;
 
    String bt1 = Integer.toBinaryString(num1);
    bt1 = String.format("%32s", bt1).replace(' ', '0');
    System.out.println(bt1);
 
    int num2 = num1 << 1;
    String bt2 = Integer.toBinaryString(num2);
    bt2 = String.format("%32s", bt2).replace(' ', '0');
    System.out.println(bt2);
 
    int num3 = num1 << 2;
    String bitset13 = Integer.toBinaryString(num3);
    bitset13 = String.format("%16s", bitset13)
      .replace(' ', '0');
    System.out.println(bitset13);
  }
}
 
// This code is contributed by akashish__


Python3




# Python code for the above approach
 
num1 = 1024
 
bt1 = bin(num1)[2:].zfill(32)
print(bt1)
 
num2 = num1 << 1
bt2 = bin(num2)[2:].zfill(32)
print(bt2)
 
num3 = num1 << 2
bitset13 = bin(num3)[2:].zfill(16)
print(bitset13)
 
# This code is contributed by Prince Kumar


C#




using System;
 
class GFG {
  public static void Main(string[] args)
  {
    int num1 = 1024;
 
    string bt1 = Convert.ToString(num1, 2);
    bt1 = bt1.PadLeft(32, '0');
    Console.WriteLine(bt1);
 
    int num2 = num1 << 1;
    string bt2 = Convert.ToString(num2, 2);
    bt2 = bt2.PadLeft(32, '0');
    Console.WriteLine(bt2);
 
    int num3 = num1 << 2;
    string bitset13 = Convert.ToString(num3, 2);
    bitset13 = bitset13.PadLeft(16, '0');
    Console.WriteLine(bitset13);
  }
}
 
// This code is contributed by akashish__


Javascript




// JavaScript code for the above approach
 
let num1 = 1024;
 
let bt1 = num1.toString(2).padStart(32, '0');
console.log(bt1);
 
let num2 = num1 << 1;
let bt2 = num2.toString(2).padStart(32, '0');
console.log(bt2);
 
let num3 = num1 << 2;
let bitset13 = num3.toString(2).padStart(16, '0');
console.log(bitset13);


Output

00000000000000000000010000000000
00000000000000000000100000000000
0001000000000000







Time Complexity: O(1) 
Auxiliary Space: O(1)

6. Right-Shift (>>)

The right shift operator is denoted by the double right arrow key (>>). The general syntax for the right shift is “shift-expression >> k”. The right-shift operator causes the bits in shift expression to be shifted to the right by the number of positions specified by k. For unsigned numbers, the bit positions that the shift operation has vacated are zero-filled. For signed numbers, the sign bit is used to fill the vacated bit positions. In other words, if the number is positive, 0 is used, and if the number is negative, 1 is used.

Note: Every time we shift a number towards the right by 1 bit it divides that number by 2.

Logical Right Shift

Logical Right Shift

Example:

Input: Left shift of 5 by 1.
Binary representation of 5 = 00101 and Left shift of 001012 by 1 (i.e, 00101 << 1)

Right shift of 5 by 1

Output: 10
Explanation: All bit of 5 will be shifted by 1 to left side and this result in 010102, Which is equivalent to 10

Input: Left shift of 5 by 2.
Binary representation of 5 = 00101 and Left shift of 001012 by 1 (i.e, 00101 << 2)

Right shift of 5 by 2

Output: 20
Explanation: All bit of 5 will be shifted by 1 to left side and this result in 101002, Which is equivalent to 20

Input: Left shift of 5 by 3.
Binary representation of 5 = 00101 and Left shift of 001012 by 1 (i.e, 00101 << 3)

Right shift of 5 by 3

Output: 40
Explanation: All bit of 5 will be shifted by 1 to left side and this result in 010002, Which is equivalent to 40

Implementation of Right shift operator:

C++




#include <bitset>
#include <iostream>
 
using namespace std;
 
int main()
{
    unsigned int num1 = 1024;
 
    bitset<32> bt1(num1);
    cout << bt1 << endl;
 
    unsigned int num2 = num1 >> 1;
    bitset<32> bt2(num2);
    cout << bt2 << endl;
 
    unsigned int num3 = num1 >> 2;
    bitset<16> bitset13{ num3 };
    cout << bitset13 << endl;
}


Java




// Java code for the above approach
 
class GFG {
    public static void main(String[] args)
    {
        int num1 = 1024;
 
        String bt1
            = String
                  .format("%32s",
                          Integer.toBinaryString(num1))
                  .replace(' ', '0');
        System.out.println(bt1);
 
        int num2 = num1 >> 1;
        String bt2
            = String
                  .format("%32s",
                          Integer.toBinaryString(num2))
                  .replace(' ', '0');
        System.out.println(bt2);
 
        int num3 = num1 >> 2;
        String bitset13
            = String
                  .format("%16s",
                          Integer.toBinaryString(num3))
                  .replace(' ', '0');
        System.out.println(bitset13);
    }
}
 
// This code is contributed by ragul21


Python




num1 = 1024
bt1 = bin(num1)[2:].zfill(32)
print(bt1)
 
num2 = num1 >> 1
bt2 = bin(num2)[2:].zfill(32)
print(bt2)
 
num3 = num1 >> 2
bitset13 = bin(num3)[2:].zfill(16)
print(bitset13)


C#




using System;
 
class Program
{
    static void Main()
    {
        int num1 = 1024;
         
        // Right shift by 1
        int num2 = num1 >> 1;
         
        // Right shift by 2
        int num3 = num1 >> 2;
 
        // Print binary representations
        string bt1 = Convert.ToString(num1, 2).PadLeft(32, '0');
        string bt2 = Convert.ToString(num2, 2).PadLeft(32, '0');
        string bitset13 = Convert.ToString(num3, 2).PadLeft(16, '0');
 
        Console.WriteLine(bt1);
        Console.WriteLine(bt2);
        Console.WriteLine(bitset13);
    }
}


Javascript




// JavaScript code for the above approach
 
let num1 = 1024;
 
let bt1 = num1.toString(2).padStart(32, '0');
console.log(bt1);
 
let num2 = num1 >> 1;
let bt2 = num2.toString(2).padStart(32, '0');
console.log(bt2);
 
let num3 = num1 >> 2;
let bitset13 = num3.toString(2).padStart(16, '0');
console.log(bitset13);
// akashish__


Output

00000000000000000000010000000000
00000000000000000000001000000000
0000000100000000







Time Complexity: O(1) 
Auxiliary Space: O(1)

Application of BIT Operators

  • Bit operations are used for the optimization of embedded systems.
  • The Exclusive-or operator can be used to confirm the integrity of a file, making sure it has not been corrupted, especially after it has been in transit.
  • Bitwise operations are used in Data encryption and compression.
  • Bits are used in the area of networking, framing the packets of numerous bits which are sent to another system generally through any type of serial interface.
  • Digital Image Processors use bitwise operations to enhance image pixels and to extract different sections of a microscopic image.


Similar Reads

Total pairs in an array such that the bitwise AND, bitwise OR and bitwise XOR of LSB is 1
Given an array arr[] of size N. The task is to find the number of pairs (arr[i], arr[j]) as cntAND, cntOR, and cntXOR such that: cntAND: Count of pairs where bitwise AND of least significant bits is 1.cntOR: Count of pairs where bitwise OR of least significant bits is 1.cntXOR: Count of pairs where bitwise XOR of least significant bits is 1. Exampl
7 min read
Maximize count of pairs whose Bitwise AND exceeds Bitwise XOR by replacing such pairs with their Bitwise AND
Given an array arr[] consisting of N positive integers, replace pairs of array elements whose Bitwise AND exceeds Bitwise XOR values by their Bitwise AND value. Finally, count the maximum number of such pairs that can be generated from the array. Examples: Input: arr[] = {12, 9, 15, 7}Output: 2Explanation:Step 1: Select the pair {12, 15} and replac
9 min read
Calculate Bitwise OR of two integers from their given Bitwise AND and Bitwise XOR values
Given two integers X and Y, representing Bitwise XOR and Bitwise AND of two positive integers, the task is to calculate the Bitwise OR value of those two positive integers. Examples: Input: X = 5, Y = 2 Output: 7 Explanation: If A and B are two positive integers such that A ^ B = 5, A &amp; B = 2, then the possible value of A and B is 3 and 6 respe
7 min read
Multiply two integers without using multiplication, division and bitwise operators, and no loops
By making use of recursion, we can multiply two integers with the given constraints. To multiply x and y, recursively add x y times. Approach: Since we cannot use any of the given symbols, the only way left is to use recursion, with the fact that x is to be added to x y times. Base case: When the numbers of times x has to be added becomes 0. Recurs
9 min read
Largest in array without using conditionals / bitwise / ternary operators
Define a function int max(int a[], int n) which returns the largest integer from an integer array consisting of n elements (without using conditionals / bitwise / ternary operators / library function to find largest Examples: Input : arr[] = {16, 14, 15, 17, 9} Output : 17 Input : arr[] = {10, 13, 11, 13} Output : 13 The idea is similar to Maximum
4 min read
Check if a number is divisible by 17 using bitwise operators
Given a number n, check if it is divisible by 17 using bitwise operators. Examples: Input : n = 34 Output : 34 is divisible by 17 Input : n = 43 Output : 43 is not divisible by 17 A naive approach will be to check it by % operator if it leaves a remainder of 0.To do division using Bitwise operators, we must rewrite the expression in powers of 2. n/
6 min read
Check if a Number is Odd or Even using Bitwise Operators
Given a number N, the task is to check whether the number is even or odd using Bitwise Operators. Examples: Input: N = 11 Output: Odd Input: N = 10 Output: Even Following Bitwise Operators can be used to check if a number is odd or even: 1. Using Bitwise XOR operator: The idea is to check whether the last bit of the number is set or not. If the las
11 min read
Generate first K multiples of N using Bitwise operators
Given an integer N, the task is to print the first K multiples of N using Bitwise Operators. Examples: Input: N = 16, K = 7 Output: 16 * 1 = 16 16 * 2 = 32 16 * 3 = 48 16 * 4 = 64 16 * 5 = 80 16 * 6 = 96 16 * 7 = 112Input: N = 7, K = 10 Output: 7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49 7 * 8 = 56 7 * 9 = 63 7 * 10
5 min read
Check if a number is divisible by 8 using bitwise operators
Given a number n, check if it is divisible by 8 using bitwise operators. Examples: Input : 16 Output :YES Input :15 Output :NO Recommended PracticeCheck if a number is divisible by 8Try It! Approach: Result = (((n &gt;&gt; 3) &lt;&lt; 3) == n). First we shift the 3 bit right then we shift the 3 bit left and then compare the number with the given nu
4 min read
Bitwise Right Shift Operators in Java
In C/C++ there is only one right shift operator '&gt;&gt;' which should be used only for positive integers or unsigned integers. Use of the right shift operator for negative numbers is not recommended in C/C++, and when used for negative numbers, the output is compiler dependent. Unlike C++, Java supports following two right shift operators. Here w
2 min read
Russian Peasant (Multiply two numbers using bitwise operators)
Given two integers, write a function to multiply them without using multiplication operator.There are many other ways to multiply two numbers (For example, see this). One interesting method is the Russian peasant algorithm. The idea is to double the first number and halve the second number repeatedly till the second number doesn't become 1. In the
5 min read
Check if a number is multiple of 9 using bitwise operators
Given a number n, write a function that returns true if n is divisible by 9, else false. The most simple way to check for n's divisibility by 9 is to do n%9. Another method is to sum the digits of n. If sum of digits is multiple of 9, then n is multiple of 9. The above methods are not bitwise operators based methods and require use of % and /. The
6 min read
What are the differences between bitwise and logical AND operators in C/C++?
A Bitwise And operator is represented as '&amp;' and a logical operator is represented as '&amp;&amp;'. The following are some basic differences between the two operators. a) The logical and operator '&amp;&amp;' expects its operands to be boolean expressions (either 1 or 0) and returns a boolean value. The bitwise and operator '&amp;' work on Inte
4 min read
Toggle case of a string using Bitwise Operators
Given a string, write a function that returns toggle case of a string using the bitwise operators in place.In ASCII codes, character ‘A’ is integer 65 = (0100 0001)2, while character ‘a’ is integer 97 = (0110 0001)2. Similarly, character 'D' is integer 68 = (0100 0100)2, while character 'd' is integer 100 = (0110 0100)2. As we can see, only sixth l
4 min read
Program for Bitwise Operators in C, C++, Java, Python, C# & JavaScript
Bitwise operators are fundamental operators used in computer programming for manipulating individual data bits. They operate at the binary level, performing operations on binary data representations. These operators are commonly used in low-level programming, such as device drivers, embedded systems, and cryptography, where manipulation at the bit
9 min read
Case conversion (Lower to Upper and Vice Versa) of a string using BitWise operators in C/C++
Given a string, write a function that converts it either from lower to upper case or from upper to lower case using the bitwise operators &amp;(AND), |(OR), ~(NOT) in place and returns the string. Many of us know that Bitwise manipulations are faster than performing arithmetic operations for a compiler as the data is stored in binary form 0's and 1
5 min read
Bitwise Operators in Java
Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types: Arithmetic Operator
6 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
Bitwise OR of Bitwise AND of all subsets of an Array for Q queries
Given two arrays arr[] of size N and queries[] of size Q, the task is to find the OR of AND of subsets of the array. In each query, you are given an index and a value, you have to replace the value at the given index of the arrays with a given value and print the OR of AND of all subsets of the array after each query. Examples: Input: arr[] = {3, 5
9 min read
Find subsequences with maximum Bitwise AND and Bitwise OR
Given an array of n elements. The task is to print the maximum sum by selecting two subsequences of the array (not necessarily different) such that the sum of bitwise AND of all elements of the first subsequence and bitwise OR of all the elements of the second subsequence is maximum. Examples: Input: arr[] = {3, 5, 6, 1} Output: 13 We get maximum A
4 min read
Find pair whose bitwise OR and bitwise AND follows the given condition
Given 2 arrays arr1[] and arr2[], of size N and M respectively, the task is to find a pair of value (say a and b) such that the following conditions are satisfied: (a | b) ? arr1[i] for all values of i in the range [0, N-1].(a &amp; b) ? arr2[j] for all values of j in the range [0, M-1]. Examples: Input: arr1[] = { 6, 9, 7, 8}, arr2[] = {2, 1, 3, 4
7 min read
Minimum possible Bitwise OR of all Bitwise AND of pairs generated from two given arrays
Given two arrays arr[] and brr[] of length N and M respectively, create an array res[] of length N using the below operations such that the Bitwise OR of all the elements in the array res[] is minimum. For every index i in arr[], choose any index j(repetitions allowed) from the array brr[] and update res[i] = arr[i] &amp; brr[j] The task is to prin
9 min read
Count ways to generate pairs having Bitwise XOR and Bitwise AND equal to X and Y respectively
Given two integers X and Y, the task is to find the total number of ways to generate a pair of integers A and B such that Bitwise XOR and Bitwise AND between A and B is X and Y respectively Examples: Input: X = 2, Y = 5Output: 2Explanation:The two possible pairs are (5, 7) and (7, 5).Pair 1: (5, 7)Bitwise AND = 5 &amp; 7 = 2Bitwise XOR = 5 ^ 7 = 5P
7 min read
Count pairs from an array whose Bitwise OR is greater than Bitwise AND
Given an array A[] consisting of N integers, the task is to count the number of pairs (i, j) such that i &lt; j, and Bitwise OR of A[i] and A[j] is greater than Bitwise AND of A[i] and A[j]. Examples: Input: A[] = {1, 4, 7}Output: 3Explanation: There are 3 such pairs: (1, 4), (4, 7), (1, 7).1) 1 | 4 (= 5) &gt; 1 &amp; 4 (= 0)2) 4 | 7 (= 7) &gt; 4
10 min read
Count pairs with equal Bitwise AND and Bitwise OR value
Given an array, arr[] of size N, the task is to count the number of unordered pairs such that Bitwise AND and Bitwise OR of each pair is equal. Examples: Input: arr[] = {1, 2, 1} Output: 1 Explanation: Bitwise AND value and Bitwise OR value all possible pairs are: Bitwise AND of the pair(arr[0], arr[1]) is (arr[0] &amp; arr[1]) = (1 &amp; 2) = 0 Bi
6 min read
Count pairs with bitwise XOR exceeding bitwise AND from a given array
Given an array, arr[] of size N, the task is to count the number of pairs from the given array such that the bitwise AND(&amp;) of each pair is less than its bitwise XOR(^). Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 8Explanation: Pairs that satisfy the given conditions are: (1 &amp; 2) &lt; (1 ^ 2)(1 &amp; 3) &lt; (1 ^ 3)(1 &amp; 4) &lt; (1
10 min read
Non-negative pairs with sum of Bitwise OR and Bitwise AND equal to N
Given an integer N, the task is to find all non-negative pairs (A, B) such that the sum of Bitwise OR and Bitwise AND of A, B is equal to N, i.e., (A | B) + (A &amp; B) = N. Examples: Input: N = 5Output: (0, 5), (1, 4), (2, 3), (3, 2), (4, 1), (5, 0)Explanation: All possible pairs satisfying the necessary conditions: (0 | 5) + (0 &amp; 5) = 5 + 0 =
5 min read
Find the triplet from given Bitwise XOR and Bitwise AND values of all its pairs
Given six positive integers representing the Bitwise XOR and Bitwise AND of all possible pairs of a triplet (a, b, c), the task is to find the triplet. Examples: Input: aXORb = 30, aANDb = 0, aXORc = 10, aANDc = 20, aXORb = 20, aANDb = 10 Output: a = 10, b = 20, c= 30 Explanation: If a = 10, b = 20, c= 30 a ^ b = 30, a &amp; b = 0 a ^ c = 10, a
7 min read
Sum of Bitwise AND of sum of pairs and their Bitwise AND from a given array
Given an array arr[] consisting of N integers, the task is to find the sum of Bitwise AND of (arr[i] + arr[j]) and Bitwise AND of arr[i] and arr[j] for each pair of elements (arr[i], arr[j]) from the given array. Since the sum can be very large, print it modulo (109 + 7). Examples: Input: arr[] = {8, 9}Output: 0Explanation: The only pair from the a
9 min read
Maximize count of pairs whose bitwise XOR is even by replacing such pairs with their Bitwise XOR
Given an array arr[] of size N, the task is to replace a pair of array elements whose Bitwise XOR is even by their Bitwise XOR. Repeat the above step as long as possible. Finally, print the count of such operations performed on the array Examples: Input: arr[] = { 4, 6, 1, 3 }Output: 3Explanation:Step 1: Remove the pair (4, 6) and replace them by t
11 min read