Python Bitwise Operators | Positive & Negative Numbers (+Examples)
Operators in programming languages allow you to manipulate data in various ways, from performing mathematical calculations to modifying values stored in variables. We have many different types of operators, such as arithmetic, comparison, logical, and bitwise operators in Python programming. Each type serves its purpose, making them indispensable for data manipulation and computation.
In this article, we’ll focus on Python bitwise operators, which operate at the binary level on the data. While these might seem difficult to grasp at first glance, they are incredibly powerful and efficient, especially in low-level system programming, network protocols, cryptography, and optimization tasks.
What Are Bitwise Operators In Python?
Bitwise operators in Python are used to perform operations on the binary representations of integers. These operators treat each integer as a sequence of bits (0s and 1s) and manipulate them directly. This allows for precise and low-level control over data, and in certain cases, bitwise operations are more efficient than arithmetic operations.
Python Bitwise operators fall into two categories:
- Logical Bitwise Operators: These are used to perform logical operations/ calculations on integers, i.e., between right operand bits and left operand bits. The Bitwise logical operators include- AND, OR, NOT, and XOR.
- Bitwise Shift Operators: Also referred to as bit shift operators, these are used to move all the operand's bits left or right a certain amount of times. These are referred to as bitwise shift operations carried on by bitwise shift operators- the left shift operator and the right shift operator, respectively.
When using Python bitwise operators, the operands are converted into binary representations of integers, and operations are performed on each bit or matching pair of bits. After that, the result in binary format is converted into the original integer format/ decimal integer literals.
When To Use Python Bitwise Operators?
Bitwise operators are handy in scenarios that require direct manipulation of data at the bit level. Some common use cases of Python bitwise operators include:
- Flags and Bit Manipulation: Use individual bits as flags to represent different states or options in programs.
- Optimizations: Bitwise operations can outperform standard arithmetic operations in certain cases, especially with large datasets.
- Data Compression: Algorithms that reduce data size often rely on bitwise manipulation.
- Cryptography: Encryption algorithms commonly employ bitwise operations to secure data.
- Low-Level System Programming: Hardware interactions often require operations at the bit level for efficiency and precision.
List Of Python Bitwise Operators
The following table outlines the six bitwise operators in Python, along with their symbols, syntax, and descriptions. In the sections that follow, we’ll look at each operator in more detail.
Name |
Operator |
Syntax |
Description |
Bitwise AND |
& |
A & B |
Compares each bit of two integers and returns 1 only if both bits are 1. If either bit is 0, the result is 0. |
Bitwise OR |
| |
A | B |
If any of the operand bit is 1 then the result is 1 else the result is 0. |
Bitwise NOT |
~ |
~A |
This is an unary bitwise operator that flips individual bits of integer/ operand. |
Bitwise XOR Operator |
^ |
A ^ B |
If the bits for both the left operand and right operand are either 0 or 1 then the result is 0; else, the result is 1. |
Right Shift Operator |
>> |
A>>n |
This bit shift operator shifts the value of the left operand to the right by the number of bits given by the right operand. |
Left Shift Operator |
<< |
A<<n |
The bit shift operator shifts the value of the left operand to the left by the number of bits given by the right operand. |
AND Python Bitwise Operator
The bitwise AND operator (&) in Python compares each bit position of two numbers/ integers and returns a result where each corresponding bit is set to 1 only if both bits in that position are 1. So, this binary operator works on the binary representations of integers, comparing pairs of bits at the same position.
Syntax Of AND Bitwise Operator In Python:
Result = operand1 & operand 2
Here,
- operand 1 and operand 2 represent the left operand and the right operand being compared, respectively.
- The ampersand symbol (&) represents the AND operator, which conducts logical conjunction on the operands.
- The result variable stores the output of the Bitwise AND operation.
Let's look at a truth table for the bitwise AND operation:
Operand 1 |
Operand 2 |
Operand 1 & Operand 2 |
0 |
0 |
0 |
0 |
1 |
0 |
1 |
0 |
0 |
1 |
1 |
1 |
Example: Consider two nonnegative integers, i.e., a = 12 and b = 25.
The binary representation of these numbers is as follows:
a = 12 (Binary: 1100)
b = 25 (Binary: 11001)
Performing Bitwise AND operation:
01100
& 11001
--------------
01000 (Result: 8 in decimal)
The simple Python program example below illustrates the code implementation of how the Python bitwise AND operator works.
Code Example:
Output:
2
Explanation:
In the simple Python code example,
- We first declare and initialize two integer variables, data1 and data2, with the values 6 and 10, respectively.
- Next, we apply the Bitwise logical operator AND (&) to perform the AND bitwise calculation on the binary representations of data1 and data2.
- The binary representation of data1 (6) is 0110, and the binary representation of data2 (10) is 1010.
- The outcome of the bitwise AND operation on these bits is 0010 in binary, which is equivalent to the decimal number 2.
- We store the outcome of the bitwise AND operation in the final variable and print it to the console using the print() statement.
An Explanation Of The Mechanism:
0110 (Binary number 6)
& 1010 (Binary number 10)
-------------------
0010 (Result after AND operation, i.e., 2)
OR Python Bitwise Operator
The bitwise OR operator in Python, represented by the pipe symbol (|), performs a bitwise inclusive OR operation between the binary representations of two integers (right and left operands). The binary bitwise operator compares each bit position of both operands and sets the corresponding result bit to 1 if either of the bits is 1; otherwise, it sets the result bit to 0.
This operator is commonly used in low-level programming tasks, such as setting specific bits within binary data or dealing with flags.
OR Python Bitwise Operator Syntax:
Result = operand1 | operand 2
Here,
- Terms operand1 and operand2 are the left operand and right operand, respectively.
- The pipe symbol (|) represents the OR operator, which performs the bitwise OR operation.
- The outcome of the bitwise OR operation is stored in the variable Result.
Truth Table:
Below is the truth table for the Python Bitwise OR operator, indicating when the operation results in 1 or 0 bit value.
Operand 1 |
Operand 2 |
Operand 1 | Operand 2 |
0 |
0 |
0 |
0 |
1 |
1 |
1 |
0 |
1 |
1 |
1 |
1 |
Example: Let’s take two integers, a = 12 and b = 25, and perform a bitwise OR operation on them.
a = 12 → 01100
b = 25 → 11001
Performing bitwise OR:
01100
| 11001
-------------
11101 (Result: 29 in decimal)
The basic Python program example below gives the code implementation of applying the Python Bitwise OR operation.
Code Example:
Output:
14
Explanation:
In the basic Python code example-
- We declare two integer variables data1 and data2 with values 6 and 10, respectively.
- The bitwise OR operator (|) is applied to their binary representations:
- data1 = 0110 (binary of 6)
- data2 = 1010 (binary of 10)
- The result is 1110 in binary, which is equivalent to the decimal number 14.
- We store the result of the bitwise OR operation in the variable final and print it ot the console.
An Explanation Of The Mechanism:
0110 (Binary number 6)
| 1010 (Binary number 10)
-------------------
1110 (Result after OR operation, i.e.,14)
Also read- Python IDLE | The Ultimate Beginner's Guide With Images & Codes!
NOT Python Bitwise Operator
The bitwise NOT operator (~) in Python performs a bitwise inversion (also called one's complement) on the binary representation of a single operand. This means that this unary Bitwise operator flips each bit of the operand: 0 becomes 1, and 1 becomes 0.
The result is the bitwise complement of the original number. In Python, this operator works in conjunction with the two's complement representation for signed integers, effectively yielding the negative of the number.
NOT Python Bitwise Operator Syntax:
result = ~ operand
Here,
- The operand is the integer on which the bitwise NOT operation is performed.
- The tilde symbol (~) represents the unary bitwise operator, NOT in Python.
- The result variable stores the output of Bitwise NOT operation.
Example: Let’s take an integer a = 12.
The binary representation of the numbers is:
a = 12 → 01100
Performing bitwise NOT:
~01100
------------
-01101 (Result: -13 in decimal)
Now, look at the Python program example that gives the code implementation of the same.
Example code:
Output:
-7
Explanation:
In the Python code example,
- We first declare and initialize an integer variable named data1 with the value 6.
- Then, we apply the Bitwise NOT operator (~) on the binary representation of data1, which flips each bit:
- 0110 becomes 1001 (bitwise inversion).
- In Python, the result is represented as a signed integer using two's complement, i.e., ~1001 = -7.
- We store the result in the variable final and print it to the console.
An Explanation Of The Working Mechanism:
(sign bit)0 110 (Binary number 6)
~
-------------------
(sign bit)1 001 (Intermediate result after one's complement operation)
Two’s complement of 1 =~(000)=111 (-7) —Final Result.
Here,
- One's Complement Operation: The one's complement operation (~) flips each bit; 0s become 1s, and 1s become 0s.
- Intermediate Result (One’s Complement Representation): The one's complement operation on the binary number (sign bit)0 110 results in the binary representation (sign bit)1001.
- Final Result (Two's Complement Representation): To obtain the 8-bit two's complement representation of a negative number, you add 1 to the one's complement result. Adding 1 to (sign bit)1 001 results in (sign bit)1 010.
XOR Python Bitwise Operator
The bitwise XOR operator (^) in Python performs a bitwise exclusive OR operation on the binary representations of two operands. It compares each pair of corresponding bits, and the result at each bit position is 1 if the bits are different; otherwise, it is 0.
This bitwise operation results in a new binary number where each bit is the result of the XOR operation between the corresponding bits of the original operands. The XOR operator is commonly used in fields like cryptography, error detection, and toggling specific bits.
XOR Python Bitwise Operator Syntax:
result = operand1 ^ operand 2
Here,
- The variables operand1 and operand2 are the two integers on which the XOR operation is performed.
- Caret symbol (^) represents the bitwise XOR operator in Python.
- The result variable stores the output of the Bitwise XOR operation.
Truth Table:
Operand 1 |
Operand 2 |
Operand 1 ^ Operand 2 |
0 |
0 |
0 |
0 |
1 |
1 |
1 |
0 |
1 |
1 |
1 |
0 |
Example: Consider two integers, say, a = 12 and b = 25.
Their binary representation is:
a = 12 → 1100 (binary)
b = 25 → 11001 (binary)
Performing bitwise XOR:
01100
^ 11001
------------
10101 (Result: 21 in decimal)
Below is an example Python program that shows the code implementation of the Bitwise XOR operator in Python.
Code Example:
Output:
12
Explanation:
In the example Python code above,
- We first declare and initialize two integer variables, data1 with the value 6 (binary: 0110) and data2 with 10 (binary: 1010).
- Then, we apply the XOR operation (^), which compares the corresponding bits of data1 and data2.
- It results in 1100 (binary), which is equivalent to the decimal number 12.
- We store this in the variable final and print it.
The Working Mechanism Of Bitwise XOR:
0110 (Binary digits for number 6)
^ 1010 (Binary digits for number 10)
-------------------
1100 (Result after XOR operation)
Right Shift Python Bitwise Operator
In Python, the right shift operator (>>) performs a bitwise right shift operation on the binary representation of a single operand. It shifts the bits of a number to the right by a specified number of positions, functioning similarly to the floor division operator. Bits that are shifted beyond the rightmost position are discarded, and zero bits are introduced on the left.
The right bitwise shift effectively divides the operand by 2 to the power of n, where n is the number of positions shifted. This operator is useful for optimizing calculations involving powers of two and is commonly used in scenarios such as integer division by powers of two or extracting specific bits from an integer.
Bitwise Operator Syntax:
Result = operand1 >> n
Here,
- The operand1 refers to the integer whose bits are to be shifted, and the number pf position is given by number n.
- The double greater-than symbol (>>) represents the right bitwise shift operator in Python.
- The result variable stores the output of the Bitwise right shift operation.
For Example: Consider two integers a = 12 and b = 3.
The binary representation is:
a = 12 → 1100 (binary)
b = 3 → 11 (binary)
Performing Bitwise Right Shift:
1100
>> 1
----------
0110 (Result: 6 in decimal)
This shows how the bits of the binary representation of the number are shifted to the right by 3. Below is a Python example program showcasing its implementation.
Code Example:
Output:
3
Explanation:
In the Python example code above-
- We initialize data1 variable with the value 6 (binary: 0110) and another integer variable n to 1.
- Then, we apply the right shift operator (>>) to shift the bits of data1 to the right by n positions.
- After shifting the binary representation of data1 (0110) by 1 position, we get 0011, which is equivalent to 3 in decimal.
- We store the outcome in the variable final and print it.
The Working Mechanism Of Right Bitwise Shift Operator:
0110 (Binary number 6)
>> 1
-------------------
0011 (Result after right shift, i.e., 3)
Here,
- Right Shifting: The right shift operation (>>1) involves moving each bit of the binary number to the right by one position.
- Result: Shifting 0110 (binary for 6) to the right by one position results in 0011, which represents 3 in decimal. The right shift operation effectively divides the number by 2 (rounded towards zero).
Left Shift Python Bitwise Operator
In Python, the left shift operator (<<) performs a bitwise left shift operation on the binary representation of a single operand. This operator shifts the bits to the left by a specified number of positions. Bits that are shifted beyond the leftmost position are discarded, and zero bits are introduced on the right.
The left shift operation effectively multiplies the operand by 2 to the power of n, where n is the number of positions shifted. This operator is commonly used for efficient multiplication by powers of two and for various bit manipulation tasks.
Syntax:
result = operand1 << n
Here,
- The operand1 is the integer whose bits are to be shifted and n is the number of positions to shift.
- The double less-than symbol (<<) represents the left shift operator in Python.
- The result variable stores the output of the bitwise left shift operation.
For example, consider two integers, i.e., a = 12 and b = 3, whose binary representation is as follows:
a = 12 → 1100 (binary)
b = 3 → 11 (binary)
Performing Bitwise Left Shift:
1100
<< 3
-----------
110000 (Result: 96 in decimal)
Look at the sample Python program below for a better understanding.
Code Example:
Output:
12
Explanation:
In the sample Python code above-
- We first declare and initialize an integer variable data1 with the value 6 (binary: 0110), and another integer variable n with the value 1.
- Next, we apply the Python bitwise left shift operator (<<) to to shift the bits of data1 to the left by n positions.
- The binary representation of data1 is 0110 and after performing a left shift by 1 position results in 1100, which is equivalent to 12 in decimal.
- We store the result in the variable final and print the same.
The Working Mechanism:
0110 (Binary number 6)
<< 1
-------------------
1100 (Result after left shift, i.e.,12)
Here,
- Left Shifting: The left shift operation (<<1) involves moving each bit to the left by one position. In this case, the entire binary form representation of 6 is shifted to the left by one position.
- Result: Shifting 0110 (binary for 6) to the left by one position effectively multiplies the number by 2. Thus, the left shift of 0110 yields 1100, representing 12 in decimal.
Check this out- Boosting Career Opportunities For Engineers Through E-School Competitions
Python Bitwise Operations And Negative Integers
In Python, integers are typically represented using a fixed number of bits (32 or 64 bits). When performing bitwise operations on negative integers, it’s crucial to understand their representation in binary, which uses a method called two's complement. This method represents negative numbers by inverting all bits of the corresponding positive number and adding 1.
Here's a brief overview of two's complement representation:
- Positive Integers: They are represented as usual in binary. For example, the decimal number 5 is represented as 101 in binary.
- Negative Integers (Two's Complement): They are represented using the two's complement. Here,
- We invert all the bits of the positive binary representation/ counterpart and add 1.
- For example, say we want to represent -5. Its binary representation is 101, and the corresponding inverted bits are 010. By adding 1, we get 011 (resulting in the two's complement representation of -5).
AND Python Bitwise Operator
The AND bitwise operator in Python works the same way for negative integers as it does for positive/ nonnegative integers. Even though negative integers in Python are represented using two's complement, the AND operator compares each bit, and the result is 1 if both bits are 1; otherwise, it is 0.
Code Example:
Output:
-4
Explanation:
In the Python program sample above-
- We first declare and initialize two integer variables, data1 and data2, with the negative values -3 and -2, respectively.
- Next, we apply the Bitwise AND operator (&) to perform a bitwise AND operation between the binary representations of data1 and data2.
- Two's complement of -3: 1101
- Two's complement of -2: 1110
- Performing 1101 & 1110 gives 1100, which is -4 in two's complement.
- We store the result in the variable final and print it.
The Working Mechanism:
-3 Two’s complement of -3 in binary = one’s complement of 2=~(010)=101
-2 Two’s complement of -2 in binary = one’s complement of 1=~(001)=110
(Sign bit)1 101 (-3 binary)
& (Sign bit)1 110 (-2 binary)
—-----------—-----------------
(Sign bit)1 100 (-4 binary)
Final output = -4
OR Python Bitwise Operator
The OR bitwise operator in Python works consistently for both negative and positive/ nonnegative integers. The crucial aspect is understanding the two's complement bit sequences representation of negative integers. The operator compares each bit and sets the result bit to 1 if at least one corresponding bit is 1.
Code Example:
Output:
-1
Explanation:
In the Python program above,
- We first declare and initialize two integer variables, data1 and data2, with the values -3 and -2, respectively.
- Next, we apply the Bitwise OR operator (|) to the binary representations of data1 and data2.
- The two's complement representation of -3 is obtained by taking the bitwise NOT (one's complement) of 2 and adding 1, i.e., ~(010) + 1 = 101.
- The two's complement representation of -2 is obtained by taking the bitwise NOT (one's complement) of 1 and adding 1: ~(001) + 1 = 110.
- Performing 1101 | 1110 results in 1111, which is -1 in two's complement. We store it in variable final ad print it as shown in the output.
The Working Mechanism:
-3 Two’s complement of -3 in binary = one’s complement of 2=~(010)=101
-2 Two’s complement of -2 in binary = one’s complement of 1=~(001)=110
(Sign bit)1 101 (-3 binary)
| (Sign bit)1 110 (-2 binary)
—---------------------------
(Sign bit)1 111 (-1 binary) Intermediate result.
Final output = -1
NOT Python Bitwise Operator
The NOT bitwise operator in Python inverts all bits, including the sign bit, for both negative and positive integers.
Code Example:
Output:
2
Explanation:
In the example Python code above-
- We first declare and initialize an integer variable data1 with the value -3.
- Next, we apply the Bitwise NOT operator (~) to the binary representation of data1.
- The two's complement representation of -3 is obtained by taking the bitwise NOT (one's complement) of 2 and adding 1, i.e., ~(010) + 1 = 101.
- The Bitwise NOT operation is performed on each bit of the two's complement representation, i.e., ~101. And the result of this operation is 010 in binary, which is equivalent to the decimal number 2.
- The outcome of this NOT operation is stored in the final variable.
The Working Mechanism:
-3 Two’s complement of -3 in binary = one’s complement of 2=~(010)=101
signbit(1) 101 (-3 binary)
~
—--—--------------
signbit(0) 010 (2 binary)
Final result=2
XOR Python Bitwise Operator
Similar to the OR operator, the XOR bitwise operator behaves consistently for negative and positive integers. The sign bit is handled similarly to other bits during this operation. The XOR operator (^) sets a bit to 1 if it is set in either operand, but not both.
Code Example:
Output:
3
Explanation:
In the Python program above-
- We first declare and initialize two integer variables, data1 and data2, with the values -3 and -2, respectively.
- Next, we apply the Bitwise XOR operator (^) between the binary representations of data1 and data2.
- The two's complement representation of -3 is obtained by taking the bitwise NOT (one's complement) of 2 and adding 1, i.e., ~(010) + 1 = 101.
- The two's complement representation of -2 is obtained by taking the bitwise NOT (one's complement) of 1 and adding 1, i.e., ~(001) + 1 = 110.
- The Bitwise XOR operation is performed on original bit patterns, i.e., 101 ^ 110. The result is 011 in binary, which is equivalent to the decimal number 3.
- The result of this XOR operation is stored in the final variable which we print.
The Working Mechanism:
Two’s complement of -3 in binary: 1…1011…101
Two’s complement of -2 in binary: 1…1101…110
1...101 (Two’s complement of -3)
^ 1...110 (Two’s complement of -2)
-------------------
0...011 (Result after XOR operation)
Final output = 3
Python Bitwise Right Shift Operator
Again, the right shift operator works consistently for both negative and positive integers. In two's complement representation, it shifts the bits of a number to the right by a specified number of positions. Depending on the sign bit, zero bits or sign bits are filled in from the left.
Code Example:
Output:
-2
Explanation:
In the Python program above,
- We first declare and initialize an integer variable, data1, with the value -3 and another integer variable, n, with the value 1.
- Next, we apply the right shift operator (>>) to the binary representation of data1.
- Next, the two's complement representation of -3 is obtained by taking the bitwise NOT (one's complement) of 2 and adding 1, i.e., ~(010) + 1 = 101.
- The Bitwise right shift operation is performed on each bit of the two's complement representation: 101 >> 1.
- The result is 110 in binary, which is equivalent to the decimal value -2.
- The result of this right shift operation is stored in the variable final.
The Working Mechanism:
Two’s complement of -3 in binary, i.e., 1 101 (Sign bit followed by binary representation of 3)
Two’s complement of 2 in binary, i.e., (010)=101 (010)=101 (One's complement of binary representation of 2)
1...101 (Two’s complement of -3)
>> 1
-------------------
1...110 (Result after right shift)
Python Bitwise Left Shift Operator
The left shift operator also works consistently for both negative and positive integers. In two's complement representation, it shifts the bits of a number to the left by a specified number of positions. Zero bits are filled in from the right, irrespective of the sign bit.
Code Example:
Output:
-6
Explanation:
In the sample Python program above-
- We first declare and initialize an integer variable data1 with the value -3, and another integer variable n with the value 1.
- Next, we apply the left shift operator (<<) to the binary representation of data1.
- The two's complement representation of -3 is obtained by taking the bitwise NOT (one's complement) of 2 and adding 1: ~(010) + 1 = 101.
- The Bitwise left shift operation is performed on each bit of the two's complement representation: 101 << 1.
- The result is 010 in binary, which is equivalent to the decimal form number -6.
- The result of this left shift operation is stored in the variable final.
The Working Mechanism:
-3 Two’s complement of -3 in binary = Two’s complement of 2=~(010)=101
1...101 (Two’s complement of -3)
<< 1
-------------------
1...010 (Result after left shift)
Also read- Flask vs Django: Understand Which Python Framework You Should Choose
The Binary Number System
The binary number system is a base-2 numeral system that uses only two digits, 0 and 1, to represent numbers. It serves as the foundational numeral system in computers and digital systems. In contrast, the decimal system (base-10) employs ten digits (0 to 9), relying on powers of 2 for binary representation.
Key Concepts
- Bit: The fundamental unit in the binary system, a bit (short for binary digit) can hold a value of either 0 or 1.
- Conversion to Decimal: To convert a binary number to decimal, you sum up the products of each bit with its corresponding power of 2. For example, the binary number 1011 is equivalent to 1⋅23+0⋅22+1⋅21+1⋅201⋅23+0⋅22+1⋅21+1⋅20, which equals 11 in decimal.
Integers are represented and interpreted in a binary number system as follows:
Signed integers use a bit to indicate the sign of the number, typically using the two's complement representation.
- In an 8-bit signed integer, the most significant bit (MSB) is the sign bit, and the remaining seven fixed-length bit patterns represent the magnitude.
- This allows signed integers to represent both positive and negative values within the specified bit range.
- For instance, in an 8-bit signed integer, extreme values range from -128 to 127(127 is the maximum integer range value).
Unsigned integers are non-negative integers represented solely by their magnitude in binary, without a dedicated sign bit. For example, in an 8-bit unsigned data type, distinct values range from 0 to 255. The absence of a sign bit allows these unsigned integer types to represent only non-negative immutable values.
The binary number system plays a crucial role, especially when working with Python bitwise operators. Python provides several bitwise operators, as discussed below, that enable the manipulation and comparison of binary numbers at the bit level with alternative integer types.
What Is Byte Order?
Byte order, or endianness, refers to the sequence in which bytes (8-bit data units) are stored in computer memory. The two common types are:
- Little-Endian: The least significant byte (LSB) is stored at the lowest memory address, with subsequent bytes stored in increasing order of significance. For examples: x86 and x86-64 architectures.
- Big-Endian: The most significant byte (MSB) is stored at the lowest memory address, with subsequent bytes stored in decreasing order of significance. For examples: PowerPC, SPARC, and Motorola 68k architectures.
Representation Example: For a 32-bit signed integer 0x123456780x123456780x12345678, the byte representation would differ based on byte order:
- Little-Endian: 78 56 34 12
- Big-Endian: 12 34 56 78
How Byte Order Affects Python Bitwise Operators?
In Python bitwise operations, the impact of byte order is particularly relevant when dealing with multi-byte fixed-point data types, such as distinct integer types represented by multiple bytes. Here’s how various bitwise operations are influenced by byte order:
- Bitwise AND (&), OR (|), XOR (^): During these operations, the corresponding bits of each byte are compared based on the system's byte order. The outcome may differ depending on whether the system is little-endian or big-endian.
- Bitwise NOT (~): This operation inverts each bit of a binary number. Its result is influenced by byte order when working with multi-byte data.
- Bitwise Shift Operators (<< and >>): These bitwise shift operators shift bits within a binary representation. The result can vary based on byte order, especially with multi-byte integers.
Application of Python Bitwise Operators
Python bitwise operators find applications in various scenarios, offering efficient solutions to specific challenges. Here are some common applications of Python bitwise operators:
- Flag and Permission Management: Bitwise compound operators are often used to manage flags and permissions compactly. Each bit in an integer can represent a specific permission or feature. By combining these bits using bitwise OR, AND, and XOR operations, developers can efficiently represent and manage complex permission systems.
- Data Compression and Optimization: In memory-constrained scenarios, Python bitwise operations can pack multiple boolean values into a single integer. This is especially useful when handling numerous flags or settings, which would otherwise consume significant memory.
- Bit Manipulation for Algorithms: Python bitwise operators are commonly employed in algorithmic challenges and optimizations. They enable efficient solutions for tasks like counting set bits, checking for powers of two, or finding the single non-repeating element in an array.
- Bitwise Filtering and Masking: Bitwise AND and OR operations are useful for filtering or masking specific bits within an integer. This approach is great for extracting or setting particular information within a fixed-length bit sequence.
- Low-Level System Programming: Python bitwise operations are used in system programming to facilitate low-level interactions with hardware, such as setting or clearing specific bit string ready in registers, and perform other low-level tasks. This is common in embedded systems programming or device driver development.
- Network Programming: Python bitwise operators are used in network programming to manipulate IP addresses, subnet masks, and perform bitwise operations on flags within network protocols.
- Encryption: Using bitwise XOR, data can be secured by converting ciphertext to plaintext and vice versa, enhancing the security of the information.
- Image Processing: Use of Python bitwise operations facilictates pixel manipulation in images. Techniques such as image masking and steganography can be implemented using these operations.
Also read- 20+ Best Python Projects Ideas
Python Bitwise Operator Overloading
In Python programming language, you can customize the behavior of bitwise operators for instances of your custom classes by overloading special or magic methods. Python bitwise operator overloading involves defining special methods such as __and__, __or__, __xor__, and __invert__ in your class. This allows instances of your class to participate in bitwise operations, just like built-in numeric types.
Here is a compact syntax for Python bitwise operator overloading:
class YourClass:
def __init__(self, value):
self.value = value
def __and__(self, other):
return YourClass(self.value & other.value)
def __or__(self, other):
return YourClass(self.value | other.value)
def __xor__(self, other):
return YourClass(self.value ^ other.value)
def __invert__(self):
return YourClass(~self.value)
def __repr__(self):
return f'YourClass({self.value})'
Here's a brief explanation of the provided syntax:
- The class keyword marks the beginning/ definition of the class called YourClass.
- The def keyword is used to create or define a function.
- The __int__ function/ method is the initializer method that sets the initial value for instances of the class.
- Next, __and__() refers to the Bitwise AND method that overloads the Bitwise AND (&) operator. It performs a bitwise AND operation between corresponding bits of two instances (self and other) and returns a new instance with the result.
- The method __or__() refers to the Bitwise OR function, which overloads the Bitwise OR (|) operator.
- Then, the __xor__() function overloads the bitwise XOR (^) operator.
- The __invert__() method overloads the bitwise NOT (~) operator. It performs a bitwise NOT operation on the instance (self) and returns a new instance with the result.
- Lastly, the __repr__() method provides an individual string format character representation of the instance for easy printing. It returns a string in the format YourClass(value).
Now, let's take a look at a code example that shows the implementation of these Python bitwise operator overloading methods.
Code Example:
Output:
BitwiseExample(1)
BitwiseExample(7)
BitwiseExample(6)
BitwiseExample(-6)
Explanation:
In the example Python program above-
- We first define a class named BitwiseExample to demonstrate overloading bitwise operators.
- Inside the class, we define an initializer method (__init__) that takes a value parameter and sets it as an attribute (self.value) for instances of the class.
- Next, we define the __and__() method to overload Python's bitwise AND (&) operator. It takes another instance (other) as a parameter, performs a bitwise AND operation between the individual bit value attribute of the current instance and the other instance, and returns a new instance of BitwiseExample with the result.
- Similarly, we define the __or__() method, which overloads Python's bitwise OR (|) operator, the __xor__() method, which overloads the bitwise XOR (^) operator, and the __invert__() method, which overloads the bitwise NOT (~) operator.
- These three methods follow a common pattern of performing the corresponding bitwise operation and returning a new instance.
- Lastly, we define the __repr__() method, which is implemented to provide a string representation of instances. It returns an individual string character in the format BitwiseExample(value).
- We then create example instances a and b with actual values 5 and 3, respectively.
- Next, we implement the bitwise methods. The Bitwise operations are demonstrated as follows:
- result_and = a & b performs bitwise AND.
- result_or = a | b performs bitwise OR.
- result_xor = a ^ b performs bitwise XOR.
- result_not = ~a performs bitwise NOT.
- Finally, we use a set of print() statements on the output of these operations, showcasing the results of the customized bitwise operations on instances a and b.
The output reflects the modified numeric values based on the bitwise operations, demonstrating how instances of the BitwiseExample class can participate in bitwise operations similar to integers.
Conclusion
Python bitwise operators provide a versatile and powerful toolkit for manipulating individual bits within integers. While they may not be the everyday choice for most developers, their role becomes crucial in scenarios requiring low-level bit manipulation. A solid understanding of bitwise AND, OR, XOR, NOT, and the left and right shift operations is essential for various tasks, from managing flags and permissions to optimizing data storage and implementing efficient algorithms.
The practical applications of Python bitwise operators are vast. They allow for compact representation of flags and permissions, optimize data storage for boolean values, and tackle algorithmic challenges with finesse. Whether it’s counting set bits in an integer or handling permissions with minimal memory consumption, bitwise operations prove their worth across multiple programming domains. As you venture into more advanced topics or engage in system programming, network protocols, or algorithmic optimizations, mastering Python bitwise operators will undoubtedly enhance your coding toolkit.
Frequently Asked Questions
Q1. Why do we use the bitwise operator?
In Python, bitwise operators are used for low-level data manipulation of individual bits within unsigned integers. These kinds of operators provide a means to perform operations at the binary level, enabling more efficient and compact representation of certain data structures and solving specific programming challenges.
The Python bitwise operators- AND, OR, XOR, and bitwise shift operators are commonly employed in scenarios such as flag and permission management, data compression, algorithmic optimizations, and low-level system programming.
Q2. Can we say whether a number is even or odd using the Bitwise AND operation?
Yes, we can determine whether a number is even or odd using the bitwise AND operation. In the binary digit representation of integers, the least significant bit (LSB) indicates whether the number is even or odd.
- For even numbers, the LSB is always 0.
- For odd numbers, the LSB is always 1.
By performing a bitwise AND operation with 1, we can extract the LSB to determine if a number is even or odd. If the result is 0, the number is even; if the result is 1, the number is odd.
Example Code:
Output:
4 is even.
7 is odd.
Q3. What is the difference between bitwise OR and XOR?
Bitwise OR (|): The Python bitwise operator OR sets a bit to 1 if at least one of the corresponding bits in the operands is 1. In other words, it combines the set bits from both operands.
For example: 5 | 3 # Binary: 0101 | 0011 → Result: 0111 (Decimal format: 7)
Bitwise XOR (^): The Python bitwise operator XOR sets a bit to 1 if exactly one of the corresponding bits in the operands is 1. It results in a 1 only if the bits are different. It results in a 1 only if the bits are different.
For example: 5 ^ 3 # Binary: 0101 ^ 0011 → Result: 0110 (Decimal format: 6)
Below is a comparison of the Bitwise OR and Bitwise XOR Truth table:
A |
B |
A | B |
A ^ B |
1 |
1 |
1 |
0 |
1 |
0 |
1 |
1 |
0 |
1 |
1 |
1 |
0 |
0 |
0 |
0 |
Q4. How to use bitwise NOT operator in Python?
We can use Python's bitwise NOT operator by using the ~ symbol before the operand. Note that it is a unary operator, which requires only a single operand to operate. It flips the bits: if a bit is 1, it becomes 0, and vice versa. It also changes the sign bit of the fixed-precision integers.
Example:
n=4
print(~n) #The output will be -5
Q5. What are bitwise vs logical operators?
Python bitwise operators perform manipulation on the bit level. They operate on every bit of the operand with its corresponding bit of the other operand. The plain integer values are first converted to binary internal representation, and the operation is performed on them at the bit level. Once the operation is done, the resulting binary bits are converted back to plain integers format/ decimal notation.
On the other hand, logical operators evaluate the logical conjunction between two boolean values or boolean expressions and yield a boolean result. The result of logical operators is always Boolean; it may be True or False.
The table below highlights the key differences between logical and Python bitwise operators.
Aspect |
Bitwise Operators |
Logical Operators |
Purpose |
Operate on individual bits of integers. |
Operate on Boolean values or expression. |
Operands |
Operands are integers/ decimal integer literals. |
Operands are Boolean values or boolean expressions. |
Use Cases |
Low-level bit manipulation, flags, etc. |
Boolean expressions are used in boolean logic and conditional statements. |
Evaluation Short Circuit |
No short-circuiting. All bits are evaluated. |
Short-circuiting consistent behavior. Stops on first False (for and) or first True (for or). |
Result Type |
Integer result. |
Boolean result. |
Q6. What is the result of the sign bit of negative and positive operands when performed bitwise AND operation?
In a 32-bit signed integer representation, the leftmost bit is often designated as the sign bit. For a 32-bit signed integer in two's complement form, the sign bit is the most significant bit (MSB). The sign bit is 0 for positive numbers and 1 for negative numbers.
When performing a bitwise AND operation between a positive and a negative operand, the result of the sign operation will always be 0. This is because the sign bit of the positive operand is 0, and the bitwise AND operation with the sign bit of the negative operand will always yield 0.
Here's a source code implementation of the same:
Output:
0b101
Explanation:
In this example, the AND operation between the positive operand (5) and the negative operand (-3) results in the binary 0001, where the sign bit is 0. The sign bit of the negative operand does not affect the result in this context, as the AND operation with 0 always yields 0.
Q7. Is the expression 9>>-1 a valid Bitwise operation?
Yes, the entire expression 9 >> -1 is a valid bitwise operation in Python. The right shift (>>) operator shifts the bits of a number to the right by a specified number of positions. In this case, the number 9 is being right-shifted by -1.
When you right-shift a number by a negative value in Python, it is treated as if you are left-shifting the number by the absolute value of that negative number. Therefore, 9 >> -1 is equivalent to 9 << 1.
Q8. What is operator overloading in Python?
Operator overloading in Python refers to the ability to define multiple behaviors for a single operator, depending on the types of its operands. This allows objects of user-defined classes to utilize standard Python operators, providing a natural and intuitive syntax. In other words, you can give special meaning to operators for instances of your classes, allowing for more elegant mathematical operations with user-defined types.
Q9. How is the built-in Modulo operator used with Python's bitwise operators?
In Python, the built-in modulo operator, represented by the percent sign (%), is used to find the remainder of the division of two numbers. While the modulo operator and bitwise operators serve different purposes, they can be combined in specific situations.
For example, using the bitwise AND operator (&) with the modulo operation can check if a number is even or odd.
Code Example:
Output:
10 is even.
In this example, the bitwise AND operation with 1 is used to check the least significant bit (LSB) of the binary representation of the number. If the LSB is 1, the number is odd; if it's 0, the number is even. This works because the binary representation of odd numbers always ends with 1, and even numbers end with 0.
Q10. How do bitwise operations handle floating-point values in Python?
Bitwise operations in Python are designed to work with integers. When applied to floating-point values, the floating-point numbers are first converted to their binary representation, which can lead to unexpected results if not properly handled. To perform bitwise operations on floating-point numbers, one would typically need to convert them to fixed-precision integers first, process them, and then convert them back to a floating-point representation if needed.
After mastering the concept of Python bitwise operators, you must also be well-versed in the following topics:
- 12 Ways To Compare Strings In Python Explained (With Examples)
- Relational Operators In Python | 6 Types, Usage, Examples & More!
- Python String.Replace() And 8 Other Ways Explained (+Examples)
- Python For Loop | Syntax & Application (With Multiple Examples)
- Python Namespace & Variable Scope Explained (With Code Examples)
- Difference Between List And Tuple In Python Explained (+Examples)
Login to continue reading
And access exclusive content, personalized recommendations, and career-boosting opportunities.
Comments
Add comment