find if bit 14 is true in a 16 bit integer in python

To find if bit 14 is true in a 16-bit integer in Python, we can use bitwise operators to perform a bitwise AND operation with the integer and a mask that has a 1 in the 14th bit position and 0 elsewhere. If the result of the AND operation is non-zero, then the 14th bit is set.

Here's an example implementation:

main.py
def is_bit_set(num: int) -> bool:
    mask = 0b0100000000000000  # mask to check 14th bit
    return (num & mask) != 0   # perform bitwise AND and check if non-zero
165 chars
4 lines

We can call this function with a 16-bit integer to check if its 14th bit is set:

main.py
num = 0b1010101010101010  # example 16-bit integer
is_set = is_bit_set(num)
print(f"The 14th bit in {bin(num)} {'is set' if is_set else 'is not set'}")  # output: The 14th bit in 0b1010101010101010 is set
205 chars
4 lines

This will output whether the 14th bit in the integer is set.

related categories

gistlibby LogSnag