简体   繁体   中英

how to do bitwise operation on escape sequence characters in python

>>>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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM