Bitwise operators in Python permit direct alteration of data at the binary level. This capability facilitates high-efficiency, low-level management in your code. Such operations are crucial in fields where memory optimization, speed, and precise control over data are of utmost importance. Areas like system programming, cryptography, embedded systems, and graphical programming extensively utilize bitwise operators. This article will delve into the nature of bitwise operators, the various types available in Python, and provide detailed examples of how each operates.
In Python, bitwise operators are characters that command the Python interpreter to carry out operations at the bit level, also known as binary manipulation. Every integer in Python is represented in binary format. These bitwise operators are unique among the Python operators because they allow direct handling of individual bits.
Note: Contrary to lower-level languages such as C or Java, Python accommodates arbitrary-length integers, meaning there are no restrictions to 8, 16, or 32 bits. You can perform bitwise operations on extremely large numbers without the concern of overflow.
Categories of Bitwise Operators in Python
Python offers six fundamental bitwise operators that enable you to manipulate bits within integers. Each operator conducts a distinct style of bit-level calculation.
Operator
Name
Example
Functionality
&
Bitwise AND
a & b
Assigns each bit a value of 1 only if both bits are 1
|
Bitwise OR
a | b
Assigns each bit a value of 1 if at least one bit is 1
^
Bitwise XOR
a ^ b
Assigns each bit a value of 1 only if the bits are different
~
Bitwise NOT
~a
Inverts all bits (1s switch to 0s and vice versa)
<<
Left Shift
a << 1
Moves bits to the left, filling with 0s to the right
>>
Right Shift
a >> 1
Moves bits to the right, removing bits on the right
Bitwise Logical Operators in Python
Bitwise Logical Operators evaluate and alter the bits of integers based on Boolean Logic Gates. There are four bitwise logical operators: AND, OR, XOR, and NOT. Let’s examine each of these operators individually.
Bitwise AND (&) Operator
The bitwise AND operator assigns each bit a value of 1 if, and only if, the corresponding bits are both 1. This operator is denoted by &.
Truth Table:
Bit A
Bit B
A & B
0
0
0
0
1
0
1
0
0
1
1
1
Example:
Python
Code Copied!
var isMobile = window.innerWidth “);
editor1043.setValue(decodedContent); // Set the default text
editor1043.clearSelection();
editor1043.setOptions({
maxLines: Infinity
});
function decodeHTML1043(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
“““html
to duplicate code to clipboard
function duplicateCodeToClipboard1043() {
const code = editor1043.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert(“Code successfully copied to clipboard!”);
data: {
language: “python”,
code: code,
cmd_line_args: “”,
variablenames: “”,
action:”compilerajax”
},
success: function(response) {
var myArray = response.split(“~”);
var data = myArray[1];
jQuery(“.output1043”).html(“
"+data+"");
jQuery(".maineditor1043 .code-editor-output").show();
jQuery("#runBtn1043 i.run-code").hide();
}
})
}
function closeOutput1043() {
var code = editor1043.getSession().getValue();
jQuery(".maineditor1043 .code-editor-output").hide();
}
// Bind event listeners to the buttons
document.getElementById("copyBtn1043").addEventListener("click", duplicateCodeToClipboard1043);
document.getElementById("runBtn1043").addEventListener("click", executeCode1043);
document.getElementById("closeoutputBtn1043").addEventListener("click", closeOutput1043);
Output:
Clarification: The binary representation of 10 is 1010, and for 4 it is 0100. Performing the AND function assesses each bit according to the truth table. Disregard the 0x values. These are hexadecimal representations of the integer.
Bitwise OR Operator
The bitwise OR operator is denoted by |. This operator assigns the bit a value of one if at least one of the bits is 1.
Truth Table:
Bit A
Bit B
A | B
0
0
0
0
1
1
1
0
1
1
1
1
Illustration:
Python
Code Copied!
Output:
Clarification: You can observe the bit representation of 10 and 4. According to the OR Truth Table, each bit was evaluated. Disregard the 0x values. Those are hexadecimal representations of the integer.
``````html
Bitwise XOR (^) Operator
The bitwise XOR operator is represented by ^. This operator assigns the bit to 1 if both of the bits differ, regardless of whether they are 0 or 1. If both bits are identical, the outcome will be zero.
function closeoutput41407() {
jQuery(".maineditor41407 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn41407").addEventListener("click", copyCodeToClipboard41407);
document.getElementById("runBtn41407").addEventListener("click", runCode41407);
document.getElementById("closeoutputBtn41407").addEventListener("click", closeoutput41407);
Output:
Explanation: The binary representation of 10 and 4 can be observed. Following the XOR Truth Table, each bit was analyzed. Disregard the 0x values; they are hexadecimal representations of the integer.
Bitwise NOT(~) Operator
The bitwise NOT operator is symbolized by ~. It flips all the bits of a number, converting 0s to 1s and 1s to 0s. This action is termed taking the 1’s complement of the number.
Nonetheless, in Python, when you utilize ~n, the output is interpreted using two’s complement representation, which is the method computers utilize to manage negative values internally.
In Python, ~n is interchangeable with -(n + 1)
Due to Python interpreting the inverted binary as a two’s complement negative integer.
Truth Table:
Bit A
~A
0
1
1
0
Example:
Python
Code Copied!
var isMobile = window.innerWidth "");
editor11980.setValue(decodedContent); // Initialize the default content
editor11980.clearSelection();
editor11980.setOptions({
maxLines: Infinity
});
function decodeHTML11980(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to duplicate code to clipboard
function copyCodeToClipboard11980() {
const code = editor11980.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code duplicated to clipboard!");
data: {
language: "python",
code: code,
cmd_line_args: "",
variablenames: "",
action: "compilerajax"
},
success: function(response) {
var myArray = response.split("~");
var data = myArray[1];
jQuery(".output11980").html("
"+data+"");
jQuery(".maineditor11980 .code-editor-output").show();
jQuery("#runBtn11980 i.run-code").hide();
}
});
}
function closeoutput11980() {
jQuery(".maineditor11980 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn11980").addEventListener("click", copyCodeToClipboard11980);
document.getElementById("runBtn11980").addEventListener("click", runCode11980);
document.getElementById("closeoutputBtn11980").addEventListener("click", closeoutput11980);
Result:
Clarification: You can observe the binary form of 10. Following the NOT Truth Table, every bit is inverted.
Why Does ~10 Yield -11?
Let's break it down step by step.
a = 10
Binary (8-bit): 00001010
Why 8 bits?
Although 10 can fit in 4 bits (1010), we utilize 8 bits for better visualization of the process; This reflects how computers generally store integers (e.g., a byte = 8 bits), aiding in interpreting the outcome as a signed binary number.
Applying bitwise NOT (~a) – this inverts every bit
~00001010 → 11110101
Understanding the result (11110101)
This is the two's complement representation of a negative integer.
To determine which negative integer:
Invert the bits again: 00001010
Add 1: 00001011 → 11
Thus, the initial result must be -11
Bitwise Shift Operators in Python
Bitwise shift operators shift the bits in a number's binary representation by a defined number of places. In Python, there are two bitwise shift operators: Left shift and Right shift.
Left Shift (<<) Bitwise Operator
The left shift operator is denoted by a << n. This operator advances the bits in the binary form of ‘a’ to the left by ‘n’ positions. A zero is appended on the right, while the leftmost bits are removed.
This operation is equivalent to multiplying the number by 2^n.
Illustration:
Python
Code Duplicated!
var isMobile = window.innerWidth "");
editor90221.setValue(decodedContent); // Initialize the default content
editor90221.clearSelection();
editor90221.setOptions({
maxLines: Infinity
});
function decodeHTML90221(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to duplicate code to clipboard
function copyCodeToClipboard90221() {
const code = editor90221.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code duplicated to clipboard!");
" + data + "");
jQuery(".maineditor90221 .code-editor-output").show();
jQuery("#runBtn90221 i.run-code").hide();
}
})
}
function closeoutput90221() {
var code = editor90221.getSession().getValue();
jQuery(".maineditor90221 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn90221").addEventListener("click", copyCodeToClipboard90221);
document.getElementById("runBtn90221").addEventListener("click", runCode90221);
document.getElementById("closeoutputBtn90221").addEventListener("click", closeoutput90221);
Output:
Explanation: In the example of 5 → 0000 0101, all bits are shifted to the left by 1 in the initial instance and by 2 in the subsequent illustration.
Right Shift (>>) Bitwise Operator
The right shift operator is denoted by >> n. This operator shifts the bits to the right by n positions. Here, the bits on the right are discarded, while the bits on the left are filled according to the sign of the integer.
For a Positive Integer, 0 is added on the left.
For a Negative Integer, 1s are added on the left to maintain the sign. This is referred to as an arithmetic shift.
It performs floor division by 2^n.
Example:
Python
Code Copied!
var isMobile = window.innerWidth ");
editor99219.setValue(decodedContent); // Set the default text
editor99219.clearSelection();
editor99219.setOptions({
maxLines: Infinity
});
function decodeHTML99219(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard99219() {
const code = editor99219.getValue(); // Get code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(".maineditor99219 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor99219 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}
function runCode99219() {
var code = editor99219.getSession().getValue();
function closeoutput99219() {
var code = editor99219.getSession().getValue();
jQuery(".maineditor99219 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn99219").addEventListener("click", copyCodeToClipboard99219);
document.getElementById("runBtn99219").addEventListener("click", runCode99219);
document.getElementById("closeoutputBtn99219").addEventListener("click", closeoutput99219);
Output:
Explanation: Here, the integer 5 is shown as 0000 0101, while -5 is depicted as 1111 1011 (due to two's complement). In the first case, 5 is right-shifted by 1, and in the second case, -5 is right-shifted by 1. For the negative number, 1s were added from the left to maintain the sign.
Bitwise Operator Overloading in Python
In Python, bitwise operators can be overloaded. Overloading allows you to define a custom functionality for bitwise operators when they are utilized with user-defined objects such as classes.
Operator overloading empowers you to modify the behavior of operators in your classes by establishing special methods, often referred to as magic methods. The bitwise operators are overloaded using the following methods.
Operator
Method
``````html
&
__and__
|
__or__
^
__xor__
~
__invert__
<<
__lshift__
>>
__rshift__
Sample:
Python
Code Copied!
var isMobile = window.innerWidth ");
editor69655.setValue(decodedContent); // Establish the default text
editor69655.clearSelection();
editor69655.setOptions({
maxLines: Infinity
});
function decodeHTML69655(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to duplicate code to clipboard
function copyCodeToClipboard69655() {
const code = editor69655.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(".maineditor69655 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor69655 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error duplicating code: ", err);
});
}
function runCode69655() {
var code = editor69655.getSession().getValue();
function closeoutput69655() {
jQuery(".maineditor69655 .code-editor-output").hide();
}
// Bind event listeners to the buttons
document.getElementById("copyBtn69655").addEventListener("click", copyCodeToClipboard69655);
document.getElementById("runBtn69655").addEventListener("click", runCode69655);
document.getElementById("closeoutputBtn69655").addEventListener("click", closeoutput69655);
Outcome:
Clarification: In this instance, when a & b is invoked, it activates the __and__() function, which executes a bitwise AND on the values of a and b, which are 6 and 3, respectively. The result is 2, thus the output is Number(2).
Summary
This article explored the different bitwise operators available in Python and elucidated how they function at the bit level. Python employs 2’s complement representation for negative integers, which clarifies the behavior of bitwise NOT and right shift operations with negative values. You also discovered how bitwise shift operators can be utilized for efficient multiplication and division by powers of 2. Moreover, you can overload bitwise operators to create custom functionality for user-defined classes. Bitwise operators find extensive applications in access management software. Mastering them will enhance your code significantly.
To elevate your skills further, consider enrolling in this Python training course for practical experience. Additionally, prepare for job interviews with Python interview queries prepared by industry professionals.
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.