Question

>>>data='\x3a'
>>>st=data.encode.('hex')
>>>st
'3a'
>>>int(st) & 1
Tracback (most recent call last):
     File "(stdin)",line 1 in <module>
ValueError:invalit literal for int() with base 10: '3a'

I would like to perform some bitwise operation on the data (which i receive from my i2c slave device)

Was it helpful?

Solution

Don't encode to hex at all; just use data directly and use the ord() function to turn the bytevalue into an integer; you don't want the hex representation here

ord(data) & 1

If you did cast to hex, you'd have to interpret the value as a hexadecimal integer:

int(st, 16) & 1

but with the encoding to hex that's more work than is required.

Demo:

>>> data = '\x3a'
>>> ord(data)
58
>>> ord(data) & 1
0
>>> int(data.encode('hex'), 16)
58
>>> int(data.encode('hex'), 16) & 1
0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top