2018年10月25日木曜日

開発環境

入門 Python 3 (Bill Lubanovic (著)、斎藤 康毅 (監修)、長尾 高弘 (翻訳)、オライリージャパン)の7章(プロのようにデータを操る)、7.3(復習問題)7-12、13、14.を取り組んでみる。

コード(Emacs)

Python 3

#!/usr/bin/env python3
import binascii
import struct

print('12.')

s = '47494638396101000100800000000000ffffff21f9' + \
    '0401000000002c000000000100010000020144003b'

gif = binascii.unhexlify(s)
print(gif)

print('13.')
print(gif[:6] == b'GIF89a')

print('14.')

width, height = struct.unpack('>HH', gif[6:10])
print(f'width: {width}, height: {height}')

# どちらも1にならず。
# 問題にビッグエンディアンの整数とあるけどリトルエンディアンとして求めてみる
width, height = struct.unpack('<HH', gif[6:10])
print(f'width: {width}, height: {height}')
# どちらも1になった。

入出力結果(Terminal, Jupyter(IPython))

$ ./sample4.py
12.
b'GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x01D\x00;'
13.
True
14.
width: 256, height: 256
width: 1, height: 1
$

原著のIntroducing Python (楽天ブックス(Kobo))を読み返してみたら、little-endianになってた。ということで誤植、翻訳ミスっぽい。

0 コメント:

コメントを投稿