Skip to content Skip to sidebar Skip to footer

How To Take Bit Number 3 From 8 Bits

I have this in hex: 08 Which is this in binary: 0000 1000 (bit positions: 7,6,5,4,3,2,1,0) Now I would like to make a bitmask in python, so I have bit position 3. Here in example 1

Solution 1:

Shift right by the bit index to have that bit in the 0th position, then AND with 1 to isolate it.

val = 0b01001000# note the extra `1` to prove this works
pos = 3
bit = (val >> pos) & 1print(bit)

outputs 1

Solution 2:

you could just do this:

def get_bit(n, pos):
    return (n >> pos) & 1

res = get_bit(n=8, pos=3) 
# 1

shift the number n left by pos bits (>> pos) and then mask away the rest (& 1).

the doc on Bitwise Operations on Integer Types may help.

Post a Comment for "How To Take Bit Number 3 From 8 Bits"