- Bitwise operators in Python (AND, OR, XOR, NOT, SHIFT)
- Inputs and outputs for AND, OR, and XOR
- Bitwise AND: &
- Bitwise OR: |
- Bitwise XOR: ^
- Bitwise operations with negative integers
- Bitwise NOT, invert: ~
- Bit shifts: >
- Related Categories
- Related Articles
- Python Bitwise Operators
- Types of Bitwise Operators in Python
- 1. Bitwise AND Operator
- 2. Bitwise OR Operator
- 3. Bitwise NOT Operator
- 4. Bitwise XOR Operator
- Bitwise Shift Operators
- 5. Bitwise Right Shift Operator
- 6. Bitwise Left Shift Operator
- Python Bitwise Operators Example
- References
- User
- FAQ: What do the operators >, &, |, ~, and ^ do?
- Preamble: Twos-Complement Numbers
- The Operators:
- Other Classes
- See Also
Bitwise operators in Python (AND, OR, XOR, NOT, SHIFT)
Python provides the bitwise operators, & (AND), | (OR), ^ (XOR), ~ (NOT, invert), > (RIGHT SHIFT).
For more information about converting binary, octal, and hexadecimal numbers and strings using bin() , oct() , hex() , and format() , see the following articles.
See the following article on how to count the number of 1 s in binary representation for integer int .
For Boolean operations on bool types ( True , False ) instead of bitwise operations, see the following article. Use and and or instead of & and | .
Inputs and outputs for AND, OR, and XOR
The inputs and outputs for each bit of AND, OR, and XOR are as follows.
Input 1 | Input 2 | AND | OR | XOR |
---|---|---|---|---|
1 | 1 | 1 | 1 | 0 |
1 | 0 | 0 | 1 | 1 |
0 | 1 | 0 | 1 | 1 |
0 | 0 | 0 | 0 | 0 |
Bitwise AND: &
Bitwise AND with the & operator:
x = 12 # 0b1100 y = 10 # 0b1010 print(x & y) print(bin(x & y)) # 8 # 0b1000
Bitwise OR: |
Bitwise OR with the | operator:
x = 12 # 0b1100 y = 10 # 0b1010 print(x | y) print(bin(x | y)) # 14 # 0b1110
Bitwise XOR: ^
Bitwise XOR with the ^ operator:
x = 12 # 0b1100 y = 10 # 0b1010 print(x ^ y) print(bin(x ^ y)) # 6 # 0b110
Bitwise operations with negative integers
Bitwise operations on negative integers are handled as if the values were expressed in two’s complement.
Note that converting a negative integer to a binary string using bin() or format() results in a minus sign rather than the two’s complement format.
x = -9 print(x) print(bin(x)) # -9 # -0b1001
To get a string expressed in two’s complement representation, perform the bitwise AND & with the maximum number of digits required. For example, use 0b1111 (= 0xF ) for 4-bit, 0xFF for 8-bit, and 0xFFFF for 16-bit.
print(bin(x & 0xFF)) print(format(x & 0xFF, 'b')) # 0b11110111 # 11110111
Keep in mind that leading zeros are omitted unless zero-padding is specified.
print(bin(x & 0b1111)) print(format(x & 0b1111, 'b')) # 0b111 # 111 print(format(x & 0b1111, '#06b')) print(format(x & 0b1111, '04b')) # 0b0111 # 0111
Bitwise NOT, invert: ~
The ~ operator yields the bitwise inversion. The bitwise inversion of x is defined as -(x+1) .
If the input value x is regarded as two’s complement and all bits are inverted, the result is equivalent to -(x+1) .
Converting ~x to a string does not yield a string with the bits of the original value inverted.
x = 9 # 0b1001 print(~x) print(bin(~x)) # -10 # -0b1010
By applying the AND operation to create a string in two’s complement representation, you can obtain a string with the inverted bits. For example, to get a 4-digit bit inverted string, specify ’04b’ with format() and pad it with zeros.
print(bin(~x & 0xFF)) print(format(~x & 0b1111, '04b')) # 0b11110110 # 0110
Bit shifts: >
Left shift and right shift with operators > :
x = 9 # 0b1001 print(x 1) print(bin(x 1)) # 18 # 0b10010 print(x >> 1) print(bin(x >> 1)) # 4 # 0b100
For negative values, the sign bit is extended and shifted, and negative values are treated as having an infinite number of ones on the left side.
x = -9 print(bin(x)) print(bin(x & 0xFF)) # -0b1001 # 0b11110111 print(x 1) print(bin(x 1)) print(bin((x 1) & 0xFF)) # -18 # -0b10010 # 0b11101110 print(x >> 1) print(bin(x >> 1)) print(bin((x >> 1) & 0xFF)) # -5 # -0b101 # 0b11111011
Understanding bit shifts for negative values as numerical values can be challenging; it’s more intuitive to consider them as two’s complement strings.
Related Categories
Related Articles
- Search for a string in Python (Check if a substring is included/Get a substring position)
- Raw strings in Python
- NumPy: Broadcasting rules and examples
- Multiple assignment in Python: Assign multiple values or the same value to multiple variables
- Convert BGR and RGB with Python, OpenCV (cvtColor)
- NumPy: Create an ndarray with all elements initialized with the same value
- Zip and unzip files with zipfile and shutil in Python
- How to use len() in Python
- Capture video from camera/file with OpenCV in Python
- pandas: Random sampling from DataFrame with sample()
- Sort a 2D list in Python
- NumPy: Make arrays immutable (read-only) with the WRITEABLE attribute
- Sign function in Python (sign/signum/sgn, copysign)
- Get the fractional and integer parts with math.modf() in Python
- numpy.arange(), linspace(): Generate ndarray with evenly spaced values
Python Bitwise Operators
Operators are used to performing operations on values and variables. These symbols carry out all kinds of computations. The value on which the operator operates on is known as Operand.
In Python, bit-wise operators are used to performing calculations on integers according to the bits. The integers are converted into binary and then bit by bit operations are performed. Then, the result is stored back in decimal format.
Types of Bitwise Operators in Python
OPERATOR | SYNTAX |
---|---|
Bitwise AND (&) | x & y |
Bitwise OR (|) | x | y |
Bitwise NOT (~) | ~x |
Bitwise XOR (^) | x ^ y |
Bitwise right shift (>>) | x>> |
Bitwise left shift(<<) | x |
1. Bitwise AND Operator
The statement returns 1 when both the bits turn out to be 1 else it returns 0.
x & y = 0101 & 0100 = 0100 = 4 (Decimal)
2. Bitwise OR Operator
The statements return 1 when either of the bits turns out to be 1 else it returns 0.
x & y = 0101 | 0100 = 0101 = 5 (Decimal)
3. Bitwise NOT Operator
The statement returns one’s complement of the number mentioned.
4. Bitwise XOR Operator
The statement returns true if any one of the bit is 1 and the other bit is 0, otherwise it returns false.
Bitwise Shift Operators
Shift operators are used to shifting the bits of a number left or right thereby multiplying or dividing the number by two respectively. They are used when we have to multiply or divide a number by two.
5. Bitwise Right Shift Operator
It shifts the bits of the number to the right and fills 0 on blank/voids right as a result. It provides a similar kind of effect as of dividing the number with some power of two.
6. Bitwise Left Shift Operator
It shifts the bits of the number to the left and fills 0 on blank/voids left as a result. It provides a similar kind of effect as of multiplying the number with some power of two.
Python Bitwise Operators Example
a = 5 b = 6 # Print bitwise AND operation print("a & b =", a & b) # Print bitwise OR operation print("a | b =", a | b) # Print bitwise NOT operation print("~a =", ~a) # print bitwise XOR operation print("a ^ b =", a ^ b) c = 10 d = -10 # print bitwise right shift operator print("c >> 1 =", c >> 1) print("d >> 1 =", d >> 1) c = 5 d = -10 # print bitwise left shift operator print("ca & b = 4 a | b = 7 ~a = -6 a ^ b = 3 c >> 1 = 5 d >> 1 = -5 cReferences
User
FAQ: What do the operators >, &, |, ~, and ^ do?
These are Python's bitwise operators.
Preamble: Twos-Complement Numbers
All of these operators share something in common -- they are "bitwise" operators. That is, they operate on numbers (normally), but instead of treating that number as if it were a single value, they treat it as if it were a string of bits, written in twos-complement binary. A two's complement binary is same as the classical binary representation for positve integers but is slightly different for negative numbers. Negative numbers are represented by performing the two's complement operation on their absolute value. So a brief summary of twos-complement binary is in order:
- 0 is written as "0"
- 1 is written as "1"
- 2 is written as "10"
- 3 is "11"
- 4 is "100"
- 5 is "101"
- .
- .
- 1029 is "10000000101" == 2**10 + 2**2 + 2**0 == 1024 + 4 + 1
Two's Complement binary for Negative Integers:
Negative numbers are written with a leading one instead of a leading zero. So if you are using only 8 bits for your twos-complement numbers, then you treat patterns from "00000000" to "01111111" as the whole numbers from 0 to 127, and reserve "1xxxxxxx" for writing negative numbers. A negative number, -x, is written using the bit pattern for (x-1) with all of the bits complemented (switched from 1 to 0 or 0 to 1). So -1 is complement(1 - 1) = complement(0) = "11111111", and -10 is complement(10 - 1) = complement(9) = complement("00001001") = "11110110". This means that negative numbers go all the way down to -128 ("10000000").
Of course, Python doesn't use 8-bit numbers. It USED to use however many bits were native to your machine, but since that was non-portable, it has recently switched to using an INFINITE number of bits. Thus the number -5 is treated by bitwise operators as if it were written ". 1111111111111111111011".
Whew! With that preamble out of the way (and hey, you probably knew this already), the operators are easy to explain:
The Operators:
x << y Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y. x >> y Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y. x & y Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0. x | y Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1. ~ x Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1. x ^ y Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1.<>
Just remember about that infinite series of 1 bits in a negative number, and these should all make sense.
Other Classes
One more point: Python allows operator overloading, so some classes may be written to allow the bitwise operators, but with some other meaning. For instance, the new sets module for Python 2.3 uses | and & for union and intersection.
See Also
BitwiseOperators (last edited 2013-07-06 12:54:41 by pranjalmittal )