動作環境
ideone (Python 3.5)
処理概要
- 8bitをI2C通信に使う
- 任意のデータ(例: 0x33)のビットをリスト形式で取得
参考
-
printing bit representation of numbers in python
- answered Jun 28 '09 at 3:00 by gahooa
- を参考に使う
- 8bit固定にならないため、先頭の0となるビットは追加するように実装した
実装 v0.1
ideone
https://ideone.com/DlqVTx
MAX_BIT = 8 # for 8 bit I2c communication
adat = 0x33 # data to be sent
binary = lambda n: n > 0 and [n & 1] + binary(n >> 1) or []
res = binary(adat)
num = MAX_BIT - len(res)
cmbnd = [0 for idx in range(num)] + res # combined 8bit
print(cmbnd)
実行結果
[0, 0, 1, 1, 0, 0, 1, 1]
備考
上記のコードはPEP8で通すと以下のようになる
do not assign a lambda expression, use a def
関連
失敗: LSBからの出力にMSBを追加していた
(追記: 2019-02-04)
LSB: Least Significant Bit
MSB: Most Significant Bit
上記のコードを使っていてI2C通信をしていたが、失敗をしていた。
StackOverflowのコード: LSBからの出力順番
先頭に0を足す: MSBからの順番
両者を混在したため、失敗していた。
0x34 (Binary: 110100)での出力
https://ideone.com/lGLx5n
[0, 0, 1, 0, 1, 1]
LSBからの出力順番であることが分かる
- 失敗
-
- 0x33 (Binary: 110011)という反対からも同じ数値を使っていた
-
- LSBかMSB順番かの確認の怠り
-
実装 v0.2: MSB, LSBの順番を訂正 (MSBからLSBの順番)
MAX_BIT = 8 # for 8 bit I2c communication
# adat = 0x33 # data to be sent
adat = 0x34 # data to be sent
binary = lambda n: n > 0 and [n & 1] + binary(n >> 1) or [] # LSB to MSB
res = binary(adat)
res.reverse()
# print(res)
num = MAX_BIT - len(res)
cmbnd = [0 for idx in range(num)] + res # combined 8bit
print(cmbnd)
結果
[0, 0, 1, 1, 0, 1, 0, 0]