zipうんぬん その2

チュートリアルのを参考に、Zipの一番最初のヘッダーを抜き出して表示してみた。

ソース

import struct

data = open('hoge.zip', 'rb').read()

start = 0
headers = struct.unpack('<LHHHHH', data[start:start+14])
signature, needver, option, comptype, filetime, filedate = headers
print 'signature',hex(signature)
print 'needver', hex(needver)
print 'option', hex(option)
print 'comptype', hex(comptype)
print 'filetime', hex(filetime)
print 'filedate', hex(filedate)

結果

signature 0x4034b50
needver 0xa
option 0x0
comptype 0x0
filetime 0x477
filedate 0x3d43


ん、あれっ、あと、これの逆をすればいいのか

最初のヘッダーを書くほう

import struct
import datetime

d = datetime.datetime.today()

signature = 0x04034B50
needver = 0xa
option =  0x0
comptype = 0x0
filetime = (d.year - 1980) << 9 | d.month << 5 | d.day
filedate = d.hour << 11 | d.minute << 5 | d.second >> 1

f = open("hoge1.zip", "wb")
f.write(struct.pack('<LHHHHH', signature, needver, option, comptype, filetime, filedate))

f.close()

バイナリの中身

00000000  50 4B 03 04 0A 00 00 00 00 00 43 3D PK........C=
0000000C  ED 1D                               ..

ここから、pythonチュートリアルの逆を・・・