LoginSignup
3
0

More than 5 years have passed since last update.

Python3 > struct パッケージ > TypeError: a bytes-like object is required, not 'int' | bytes-like objectのリテラル定義 | unpackできた

Last updated at Posted at 2018-02-27
動作環境
ideone > Python 3.5

とあるセンサーの測定値読取りコード(at GitHub)においてstructのpack(), unpack()を使っている例がある。

structは使ったことがないので、試用してみる。

(追記 2018/02/27)
pack()の方は使ったことがあったが、忘れていた。。。

code v0.1 > TypeError: a bytes-like object is required, not 'int'

import struct

pi = 0x3141

msb, lsb = struct.unpack('>HB', pi)
print(msb)
print(lsb)

run
Traceback (most recent call last):
  File "./prog.py", line 5, in <module>
TypeError: a bytes-like object is required, not 'int'

code v0.2 > unpackできた

  • little endianで
  • unsigned short(H)をmsbとして
  • unsigned char(B)をlsbとして
  • 取得する

import struct

#pi = 0x3141
pi = b'\x31\x41\x59'

msb, lsb = struct.unpack('>HB', pi)
print(msb)  # 12609 (0x3141)
print(lsb)  # 89 (0x59)

run
12609
89

link

3
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
3
0