Skip to content
# Python Bitwise Operators

## Bitwise Operators in Python

### Bitwise AND operator (&):

### Bitwise OR operator (|):

### Bitwise XOR operator (^):

### Bitwise complement operator (~)

### Bitwise Operators with Flags:

### Quiz: Bitwise Operators in Python

#### Question 1:

What is the result of the bitwise AND operation for the binary representations of 5 and 3?

#### Question 2:

Which bitwise operator is used to flip the bits of its operand?

#### Question 3:

What is the binary representation of the result when the bitwise XOR operator is applied to 5 and 3?

#### Question 4:

How would you set the third bit (counting from right to left) of the number 5 to 1?

#### Question 5:

What is the purpose of the right shift operator (>>)?

#### Question 6:

How can you check if a number is odd using bitwise operators?

#### Question 7:

What bitwise operation can be used to combine two lists into a single list containing all unique elements?

#### Question 8:

In Python, how are negative numbers represented in binary using two’s complement form?

#### Question 9:

Which bitwise operator is commonly used to toggle a flag?

#### Question 10:

How can you extract the binary representation of the significand (mantissa) of a floating-point number using bitwise operators?

- الرئيسية
- أحدث المقالات
- دارت | فلاتر

Python bitwise operators are used to manipulate the binary representations of numbers. There are six bitwise operators in Python: AND (&), OR (|), XOR (^), complement (~), left shift (<<), and right shift (>>). These operators allow you to perform operations such as setting specific bits, clearing bits, and shifting bits to the left or right. Understanding how these operators work is essential for tasks that involve working with binary data or optimizing code for performance.

Here are some examples of Python bitwise operators:

Returns a 1 in each bit position where both operands have a 1.

a = 5 # binary representation of 5 is 0101

b = 3 # binary representation of 3 is 0011

c = a & b # bitwise AND of 5 and 3 is 0001 (decimal 1)

print(c) # output: 1

Returns a 1 in each bit position where at least one operand has a 1.

a = 5 # binary representation of 5 is 0101

b = 3 # binary representation of 3 is 0011

c = a | b # bitwise OR of 5 and 3 is 0111 (decimal 7)

print(c) # output: 7

Returns a 1 in each bit position where only one operand has a 1.

a = 5 # binary representation of 5 is 0101

b = 3 # binary representation of 3 is 0011

c = a ^ b # bitwise XOR of 5 and 3 is 0110 (decimal 6)

print(c) # output: 6

Flips the bits of its operand.

a = 5 # binary representation of 5 is 0101

c = ~a # bitwise complement of 5 is 1010 (decimal -6 due to two’s complement representation)

print(c) # output: -6

Left shift operator (<<): Shifts the bits of its first operand to the left by the number of positions specified by the second operand.

a = 5 # binary representation of 5 is 0101

c = a << 2 # left shift 5 by 2 bits is 010100 (decimal 20)

print(c) # output: 20

Right shift operator (>>): Shifts the bits of its first operand to the right by the number of positions specified by the second operand.

a = 5 # binary representation of 5 is 0101

c = a >> 2 # right shift 5 by 2 bits is 0001 (decimal 1)

print(c) # output: 1

Here are some more uses of Python bitwise operators:

Setting and Clearing Bits:

You can use bitwise operators to set or clear specific bits in a binary number. To set a bit, use the OR operator (`|`

) with a number that has a 1 in the position you want to set. To clear a bit, use the AND operator (`&`

) with a number that has a 0 in the position you want to clear.

# Set the third bit (counting from right to left) of 5 to 1

a = 5

a = a | 0b100 # 0b100 is binary for 4, which has a 1 in the third position

print(bin(a)) # output: 0b101

# Clear the second bit of 5

a = 5

a = a & 0b1011 # 0b1011 is binary for 11, which has a 0 in the second position

print(bin(a)) # output: 0b1

Checking for Even or Odd Numbers:

You can use bitwise operators to check whether a number is even or odd. An even number always has a 0 in the least significant bit (the rightmost bit), while an odd number always has a 1 in the least significant bit.

# Check if a number is even or odd

a = 5

if a & 1 == 0:

print(“Even”)

else:

print(“Odd”)

# output: Odd

Bitwise operators are often used with flags to represent multiple binary options in a single integer. You can set or clear individual flags by using the OR and AND operators, and you can check if a flag is set by using the AND operator.

# Define some flags as binary constants

FLAG_A = 0b0001

FLAG_B = 0b0010

FLAG_C = 0b0100

FLAG_D = 0b1000

# Set flags A and C, and clear flag B

flags = FLAG_A | FLAG_C & ~FLAG_B

print(bin(flags)) # output: 0b101

# Check if flag C is set

if flags & FLAG_C:

print(“Flag C is set”)

else:

print(“Flag C is not set”)

# output: Flag C is set

These are just a few examples of the many uses of Python bitwise operators. With some creativity, you can use them to perform all kinds of bit-level manipulations and optimizations.

**Here are some more uses of Python bitwise operators:**

**Masking: **

You can use bitwise operators to extract a specific set of bits from a binary number. To extract the bits, you first create a binary number with 1’s in the positions you want to extract and 0’s elsewhere. Then, you use the AND operator with the original number to extract only the desired bits.

# Extract the low 4 bits of a number

a = 0b11011011

mask = 0b1111 # mask has 1’s in the low 4 bits and 0’s elsewhere

result = a & mask

print(bin(result)) # output: 0b1011

**Signed Integers: **

In Python, integers are represented in two’s complement form, where the most significant bit (MSB) is used as a sign bit. This means that negative numbers have a 1 in the MSB, while positive numbers have a 0. You can use bitwise operators to perform arithmetic operations on signed integers.

# Addition of signed integers

a = -5

b = 3

c = a + b

print(c) # output: -2

# Multiplication of signed integers

a = -5

b = 3

c = a * b

print(c) # output: -15

**Bitwise Operators with Lists: **

You can use bitwise operators to perform set operations on lists. For example, you can use the OR operator to combine two lists into a single list that contains all the unique elements from both lists.

# Combine two lists using the OR operator

a = [1, 2, 3]

b = [2, 3, 4]

c = list(set(a) | set(b))

print(c) # output: [1, 2, 3, 4]

These are just a few more examples of the many uses of Python bitwise operators. Bitwise operators are a powerful tool for working with binary data and optimizing code, so it’s worth taking the time to learn how to use them effectively.

**Here are some more uses of Python bitwise operators:**

**Binary Representation of Floating Point Numbers: **

You can use bitwise operators to extract the binary representation of the significand (mantissa) of a floating-point number. This can be useful in applications such as graphics programming.

# Extract the significand of a floating-point number

import struct

x = 1.5

bits = struct.pack(‘!f’, x)

bits = struct.unpack(‘!I’, bits)[0]

bits = (bits & 0x007FFFFF) | 0x3F800000

result = struct.pack(‘!f’, struct.unpack(‘!f’, struct.pack(‘!I’, bits))[0])

print(bin(bits)) # output: 0b10111100000000000000000000000000

print(result) # output: b’\x3f\x80\x00\x00′

**Bitwise Operators with Bit Flags: **

You can use bitwise operators to store multiple boolean values in a single integer using bit flags. For example, you can use the OR operator to set a flag, the AND operator to clear a flag, and the XOR operator to toggle a flag.

# Set, clear, and toggle bit flags

FLAG_A = 0b0001

FLAG_B = 0b0010

FLAG_C = 0b0100

flags = FLAG_A | FLAG_B

flags = flags & ~FLAG_A

flags = flags ^ FLAG_B

print(bin(flags)) # output: 0b0010

**Bitwise Operators with Bytes: **

You can use bitwise operators to manipulate bytes in a binary file or network communication. For example, you can use the AND operator to mask out certain bits, the OR operator to set specific bits, and the XOR operator to toggle bits.

# Manipulate bytes using bitwise operators

data = b’\x01\x23\x45\x67\x89\xAB\xCD\xEF’

# Mask out the low 4 bits of the first byte

data = bytes([data[0] & 0xF0]) + data[1:]

# Set the high bit of the second byte

data = data[:1] + bytes([data[1] | 0x80]) + data[2:]

# Toggle the low 2 bits of the third byte

data = data[:2] + bytes([data[2] ^ 0x03]) + data[3:]

print(data.hex()) # output: 0123456789ABCF

These are just a few more examples of the many uses of Python bitwise operators. Bitwise operators are a powerful tool for working with binary data and optimizing code, so it’s worth taking the time to learn how to use them effectively.

What is the result of the bitwise AND operation for the binary representations of 5 and 3?

a) 6

b) 1

c) 7

d) -6

Which bitwise operator is used to flip the bits of its operand?

a) AND (&)

b) OR (|)

c) XOR (^)

d) Complement (~)

What is the binary representation of the result when the bitwise XOR operator is applied to 5 and 3?

a) 0100

b) 0110

c) 0011

d) 1100

How would you set the third bit (counting from right to left) of the number 5 to 1?

a) 5 = 5 & 0b100

b) 5 = 5 | 0b100

c) 5 = 5 ^ 0b100

d) 5 = 5 << 2

What is the purpose of the right shift operator (>>)?

a) Shifts the bits to the left

b) Flips the bits of its operand

c) Shifts the bits to the right

d) Extracts a specific set of bits

How can you check if a number is odd using bitwise operators?

a) if a & 1 == 0:

b) if a | 1 == 1:

c) if a ^ 1 == 1:

d) if a << 1 == 1:

What bitwise operation can be used to combine two lists into a single list containing all unique elements?

a) AND (&)

b) OR (|)

c) XOR (^)

d) Complement (~)

In Python, how are negative numbers represented in binary using two’s complement form?

a) MSB is 0

b) MSB is 1

c) LSB is 0

d) LSB is 1

Which bitwise operator is commonly used to toggle a flag?

a) AND (&)

b) OR (|)

c) XOR (^)

d) Complement (~)

How can you extract the binary representation of the significand (mantissa) of a floating-point number using bitwise operators?

a) OR operator

b) AND operator

c) XOR operator

d) Right shift operator

Answers:

1-b) 1

2-d) Complement (~)

3-b) 0110

4-b) 5 = 5 | 0b100

5-c) Shifts the bits to the right

6-a) if a & 1 == 0:

7-b) OR (|)

8-b) MSB is 1

9-c) XOR (^)

10-b) AND operator

Main Content