【问题标题】:How to extract the LSB from a byte in C and Python?如何从 C 和 Python 中的字节中提取 LSB?
【发布时间】:2017-09-03 08:29:54
【问题描述】:

我正在通过蓝牙串行向我的 Raspi 3 和我的 Arduino 发送一个字节。

例如0b00000011(模式),0b01000001(模式),0b10010000(方向)

LSB表示该字节是方向命令还是切换模式的指令,所以我需要在Arduino C和Python中提取它。

有人知道怎么做吗? 提前致谢!

【问题讨论】:

  • value&1 两种语言。
  • 提取数字的某些位的值的常用方法是使用按位“与”操作屏蔽其他位。 Python 和 C 以相同的方式拼写该运算符:&.
  • 把整数变成binary string;获取最后一个字符,转换回 int。
  • @wii 效率太低了。

标签: python c python-2.7 python-3.x arduino


【解决方案1】:

使用位运算:

C 代码

char b = 0x01;

if( b & 0x01 ) {
   // LSB is set
}
else {
   // LSB is not set
}

Python 代码

b = 0x01
if (b&0x01)==0x01 :
    # LSB is set
else:
    # LSB is not set

LSB = Least S重要B它(在你的情况下)

【讨论】:

  • 出现此错误:Traceback (last last call last): File "/home/pi/Desktop/test.py", line 11, in if (b & 0x01): TypeError: & 不支持的操作数类型:'bytes' 和 'int'
  • 好的,你知道用python怎么做吗?
猜你喜欢
  • 1970-01-01
  • 2021-07-14
  • 2012-04-14
  • 2014-07-09
  • 2015-04-14
  • 1970-01-01
  • 2015-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多