1
votes

Let's say I have a string representing a hexadecimal value such as "0x4", binary represented as 0100. If I want test whether the nth bit is set to 1, and where I count starting from the least significant bit (meaning in this example that only the 3rd bit is 1) how can I do this in the most elegant way?

I doubt the way I am doing is very elegant or efficient. bits = '{0:08b}'.format(int(0x4, 16)) and then check if str(bits[-3]) is "1"

bits = '{0:08b}'.format(int(0x4, 16))
if str(bits[-3]) == "1":
    print "Bit is set to 1"

I'd like a neat way of doing this, e.g. using bitwise operators or shifting.

4

4 Answers

1
votes

To test if a bit is set, use the bitwise & on a bit mask of just that bit:

>>> bool(12 & 0b0100)
True

To get a bit mask set at the n-th position, bit-shift a 1 by n-1 positions:

>>> n = 3
>>> 1 << n-1
4
>>> bin(1 << n-1)
'0b100'

Combined, you can directly check whether a specific bit is set:

>>> def bitset(number, n):
...     """Test whether ``number`` has the ``n``'th bit set"""
...     return bool(number & 1 << n - 1)
...
>>> bitset(0x4, 3)

If your input is a string (instead of generating a string from an integer), use int to convert it:

>>> bitset(int('0x4', 16), 3)
0
votes

Usually you'd use bitwise operators for that:

if 4 & 1 << n:
    print('Bit', n, 'is set')
0
votes

You could use the bin() function to convert an integer to a binary string:

>>> n = int('0x4', 16)
>>> n
4
>>> bin(n)
'0b100'
>>> bin(n)[-3] == '1'
True

A more efficient way would be to operate on the integer directly using bitwise operators:

>>> bool(n & 1<<2)  # shift "1" 2 bits to the left and use bitwise and
True
0
votes

you can use:

def check_nth_bit(str_hex, nth_bit):
    return (int(str_hex, 16) & 2 **(nth_bit - 1)) >> (nth_bit - 1) == 1

print(check_nth_bit('0x4', 3))
print(check_nth_bit('0x4', 1))

output:

True
False