Ask Your Question
2

How can bit masking be implemented in Python?

asked 2023-06-28 08:12:45 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-28 08:15:01 +0000

devzero gravatar image

Bit masking can be implemented in Python using the bitwise operators such as bitwise and (&), bitwise or (|), bitwise xor (^), bitwise not (~), and left shift (<<) and right shift (>>).

To set a particular bit in a number to 1, we can use the bitwise or operation with the corresponding bit position. For example, to set the 3rd bit of a number to 1, we can use the following code:

num = 5 # binary representation is 101 mask = 1 << 3 # shift 1 by 3 bits to get the mask 1000 num = num | mask # bitwise or operation to set the 3rd bit to 1 print(num) # output is 13, binary representation is 1101

To clear a particular bit in a number to 0, we can use the bitwise and operation with the inverted mask. For example, to clear the 3rd bit of a number to 0, we can use the following code:

num = 13 # binary representation is 1101 mask = ~(1 << 3) # shift 1 by 3 bits, invert it to get the mask 0111 num = num & mask # bitwise and operation to clear the 3rd bit to 0 print(num) # output is 5, binary representation is 0101

Other bitwise operations can be similarly implemented to manipulate the bits of a number in Python.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-28 08:12:45 +0000

Seen: 8 times

Last updated: Jun 28 '23