0

Unfortunately python can't read a bit from byte.I have the following some bits:

var1 = 0b00001111 => 15 in decimal
var2 = 0b 00000010 => 2 in decimal  

I need to check second bit in var2, or 3th bit in var1.

How to check those?

PersianGulf
  • 2,845
  • 6
  • 47
  • 67
  • 1
    What do you mean by "check" and "read a bit from a byte"? If you want to see if the bit is set, why not `(0b10 >> 1) & 1` or `(0b1111 >> 2) & 1`? – ggorlen Aug 19 '19 at 06:09
  • @ggorlen Your comment can be an answer in itself. – Ganesh Tata Aug 19 '19 at 06:11
  • 1
    Not necessary because surely this is a duplicate... just hunting for it, and I'm not really sure what OP is asking here. – ggorlen Aug 19 '19 at 06:13

2 Answers2

0

If you have 0010 and want to check second bit is true or false, You can and with 2:

if (0b0010 & 2) == 2 :
    print("two is OK")
if (0b0110 & 4) == 4:
    print("four is ok")
PersianGulf
  • 2,845
  • 6
  • 47
  • 67
-3

You can run something like bin(var2)[::-1][1] to get the second least significant bit.

tehtea
  • 316
  • 3
  • 12
  • 4
    What's the point of converting a binary number to a string just to test whether a bit is set? Doesn't this pretty much defeat the purpose of using binary? – ggorlen Aug 19 '19 at 06:10
  • True that, how about bitwise AND-ing then? – tehtea Aug 19 '19 at 06:13