0

I am pulling byte wide data from a processor, and trying to extract one bit/flag for status. I pull the data byte from 0x1B, and then mask against 0x08, which is supposed to leave the 4th bit. In normal operation it takes some time for the bit to flip - so I iterate on pulling the bit and testing it

STATUS_FOC = []
STATUS = []
FOC_Mask = []
while x <= 100:
     STATUS = bin(sys.Read(0x1B))
     print 'status', STATUS
     FOC_Mask = bin(0x08)
     print 'FOC', FOC_Mask

     STATUS_FOC = STATUS & FOC_Mask

No matter what I do to the variables Python insists in the last line that I am trying to do a logical AND of two strings. Output of STATUS and FOC_Mask are as follows:

status 0b11010000 FOC 0b1000

which I read as binaries, and yet the program crashes over the last line saying that it can't do an '&' operation on strings. Help

1
  • 1
    Well, yes. bin() returns a string. Stop using it. Commented Apr 16, 2016 at 3:58

2 Answers 2

2

The bin() function returns a string. You don't need it in your code. Simply do:

STATUS_FOC = []
STATUS = []
FOC_Mask = []
# x = 0
while x <= 100:
     STATUS = sys.Read(0x1B)
     print 'status', STATUS
     FOC_Mask = 0x08
     print 'FOC', FOC_Mask
     STATUS_FOC = STATUS & FOC_Mask
     # x += 1

This should work, I have no way to test it using your system. I have also added a hint to increment x otherwise Python will give you an error on the while condition, or your loop will last forever if x is defined elsewhere, unless that is what you wanted.

Sign up to request clarification or add additional context in comments.

Comments

0

bin is giving you a sting representation of a binary number. In order to use the & bitwise operator, both values much be ints

In [10]: status = bin(0x1B)

In [11]: print 'status', status
status 0b11011

In [12]: mask = bin(0x08)

In [13]: print 'foc ', mask
foc  0b1000

In [14]: status_foc = int(status, 2) & int(mask, 2)

In [15]: print 'status_foc', status_foc
status_foc 8

In [16]: status_foc = bin(status_foc)

In [17]: print 'status_foc', status_foc
status_foc 0b1000

The second argument in int('string', 2) makes it base 2, or binary.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.