简体   繁体   English

如何在python中对转义序列字符进行按位运算

[英]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) 我想对数据执行一些按位运算(我从我的i2c从设备接收到的数据)

Don't encode to hex at all; 根本不编码为十六进制; just use data directly and use the ord() function to turn the bytevalue into an integer; 只需直接使用data并使用ord()函数将字节值转换为整数即可; 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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