LoginSignup
0
0

More than 5 years have passed since last update.

Python 3 > データを8bitのリスト形式で返す | PEP8: do not assign a lambda expression, use a def | 失敗: LSBからの出力の前にMSBを追加していた

Last updated at Posted at 2019-02-04
動作環境
ideone (Python 3.5)

処理概要

  • 8bitをI2C通信に使う
  • 任意のデータ(例: 0x33)のビットをリスト形式で取得

参考

実装 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からの出力順番であることが分かる

  • 失敗
    • 1. 0x33 (Binary: 110011)という反対からも同じ数値を使っていた
    • 2. 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]
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0