Complete Reference for Bitwise Operators in Programming/Coding
Last Updated :
28 Dec, 2023
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 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 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 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__
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.
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.
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.
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__
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 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 << " \n Inverting using NOT operator (with sign bit): " << ( ~ a );
cout << " \n Inverting 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 Example:
Input: Left shift of 5 by 1. Binary representation of 5 = 00101 and Left shift of 00101 2 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 01010 2, Which is equivalent to 10
Input: Left shift of 5 by 2. Binary representation of 5 = 00101 and Left shift of 00101 2 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 10100 2, Which is equivalent to 20
Input: Left shift of 5 by 3. Binary representation of 5 = 00101 and Left shift of 00101 2 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 01000 2, 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 Example:
Input: Left shift of 5 by 1. Binary representation of 5 = 00101 and Left shift of 00101 2 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 01010 2, Which is equivalent to 10
Input: Left shift of 5 by 2. Binary representation of 5 = 00101 and Left shift of 00101 2 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 10100 2, Which is equivalent to 20
Input: Left shift of 5 by 3. Binary representation of 5 = 00101 and Left shift of 00101 2 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 01000 2, 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
How to set height equal to dynamic width (CSS fluid layout) ?
To create a fluid layout in CSS, set an element's height to the same value as its dynamic width. This makes the layout more adaptable and responsive since the element's height will automatically change depending on the viewport's width. It is possible to determine the element's height by using the p
2 min read
How to Set Height Equal to Dynamic Width (CSS fluid layout) in JavaScript ?
A key component of constructing a contemporary website in web development is developing an adaptable and dynamic layout. Setting the height of an element equal to its dynamic width, often known as a CSS fluid layout, is a common difficulty in accomplishing this. When the screen size changes and you
4 min read
How to Create Equal Height Columns in CSS ?
Equal Height Columns in CSS refer to ensuring that multiple columns in a layout have the same height, regardless of the content inside each column. This can be achieved using modern CSS techniques like Flexbox, CSS Grid, or the Table display property. Table of Content Using FlexUsing GridUsing Table
3 min read
How to make div height expand with its content using CSS ?
When designing a webpage, ensuring that a div adjusts its height according to its content is important for creating a flexible and responsive layout. By using CSS, you can easily make a div adapt to varying content sizes, which is particularly useful when dealing with dynamic or unpredictable conten
3 min read
How to Set Viewport Height & Width in CSS ?
Set viewport height and width in CSS is essential for creating responsive and visually appealing web designs. We'll explore the concepts of setting viewport height and width by using various methods like CSS Units, Viewport-Relative Units, and keyframe Media Queries. Table of Content Setting viewpor
3 min read
How to Stretch Elements to Fit the Whole Height of the Browser Window Using CSS?
To stretch elements to fit the whole height of the browser window using CSS, you can use "vh" units, where "1vh" equals 1% of the viewport height, so setting the height to "100vh" spans the entire height. Approach: Using CSS height PropertyIn this approach, we are using the Height property to fit th
1 min read
How to get the height of device screen in JavaScript ?
Given an HTML document which is running on a device. The task is to find the height of the working screen device using JavaScript. Prerequisite - How to get the width of device screen in JavaScript ? Example 1: This example uses window.innerHeight property to get the height of the device screen. The
2 min read
How to fit text container width dynamically according to screen size using CSS ?
In this article, we have given a text paragraph and the task is to fit the text width dynamically according to screen size using HTML and CSS. Some of the important properties used in the code are as follows- display-grid: It helps us to display the content on the page in the grid structure.grid-gap
7 min read
How to Adjust the Width and Height of an iframe to Fit the Content Inside It?
When using the <iframe> tag in HTML, the content inside the iframe is displayed with a default size if the width and height attributes are not specified. Even if the dimensions are specified, it can still be difficult to perfectly match the iframe’s size with the content inside it. This can be
4 min read
jQWidgets jqxLayout height Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxLayout is used for representing a jQuery widget that is used for the creation of complex layouts with nested
2 min read
How to Make Flexbox Items of Same Size Using CSS?
To make Flexbox items the same size using CSS, you can use various properties to control the dimensions of the items and ensure consistency in layout. By default, Flexbox items can have different sizes based on their content, but with a few CSS changes, you can make them uniform. 1. Using Flex Prope
5 min read
How to Specify Height to Fit-Content with Tailwind CSS ?
Specifying height to fit-content in Tailwind CSS means setting an element’s height to automatically adjust based on its content. Tailwind provides the h-fit utility class, which ensures the element's height dynamically adapts to its content's size. Adjusting Height with h-fit in Tailwind CSSThis app
2 min read
How to detect the change in DIV's dimension ?
The change in a div's dimension can be detected using 2 approaches: Method 1: Checking for changes using the ResizeObserver Interface The ResizeObserver Interface is used to report changes in dimensions of an element. The element to be tracked is first selected using jQuery. A ResizeObserver object
4 min read
How to Change the Height and Width of an Element with JavaScript?
To change the height and width of an element using JavaScript, you can directly manipulate the style property of the element. Here’s a simple guide on how to do it: Example:[GFGTABS] HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <m
1 min read
Primer CSS Layout width and height
Primer CSS is a free open-source CSS framework that is built with the GitHub design system to provide support to the broad spectrum of Github websites. It creates the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are ste
5 min read
How to Create Equal Width Table Cell Using CSS ?
Creating equal-width table cells using CSS refers to adjusting the table's layout so that all columns maintain the same width. This technique ensures a consistent and organized appearance, making the table content easier to read and visually balanced. Here we are following some common approaches: Ta
3 min read
How to Set Width and Height of Span Element using CSS ?
The <span> tag is used to apply styles or scripting to a specific part of text within a larger block of content. The <span> tag is an inline element, you may encounter scenarios where setting its width and height becomes necessary. This article explores various approaches to set the widt
2 min read
How to Set 100% Height with Padding/Margin in CSS ?
In this article, we'll explore CSS layouts with 100% width/height while accommodating padding and margins. In the process of web page design, it is often faced with scenarios where the intention is to have an element fill the entire width and/or height of its parent container, while also maintaining
3 min read
How to give a div tag 100% height of the browser window using CSS
CSS allows to adjustment of the height of an element using the height property. While there are several units to specify the height of an element. Set the height of a <div> to 100% of its parent container with height: 100%, or use height: 100vh; for a full viewport height, ensuring the <div
2 min read