Python语言: head.py 输出文件开头的8个字节的二进制表示

作者:半瓶墨水 链接:http://www.2maomao.com/blog/output-header-of-file-in-python/

最近在写一个在线favicon编辑器,其ico格式很让人不爽,写了个工具生成ico格式的文件
为了手动检查生成结果,写了这个脚本检查其文件头内容:

Python语言: head.py 输出文件开头的8个字节的二进制表示
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Recently I start to write an ico file maker
#   this script helps on analyze the file header
#
# Usage:
#   head xxx.ico    - output 16 bytes
#   head xxx.ico 32 - output 32 bytes
#
import sys
f = open(sys.argv[1], "rb")
L = 16
if len(sys.argv) >= 3:
  L = int(sys.argv[2])
bytes = f.read(L)
for i in range(0, len(bytes), 8):
  print bytes[i:i+8]

xbytes = ["%02x" % ord(b) for b in bytes]
print
for i in range(0, len(bytes), 8):
  print "x " + " ".join(xbytes[i:i+8])

def to_bits(b):
  bs = []
  while b:
    bs.append(b&1)
    b>>=1
  bs = map(str, bs)
  bs.reverse()
  return "".join(bs).zfill(8)

bits = [to_bits(ord(b)) for b in bytes]
print
for i in range(0, len(bytes), 8):
  print "b " + " ".join(bits[i:i+8])

  • Share/Bookmark

2 Tweets

共 4 条评论

  • realfun 九月 9th, 2009 7:23 下午

Python语言: head.py 输出文件开头的8个字节的二进制表示: 最近在写一个在线favicon编辑器,其ico格式很让人不爽,写了个工具生成ico格式的文件 为了手动检查生成结果,写了这个脚本检查其文件头内容: .. http://bit.ly/QUc2i

This comment was originally posted on Twitter

  • est 九月 9th, 2009 7:25 下午

博主的方法太麻烦了

python -c “print open(’C:\\windows\\notepad.exe’, ‘rb’).read(8).encode(’hex’)”

@est 你这个是很简单,跟我这个程序最初的版本一样
不过后来随着应用的需要,8bytes已经不够用,不光是16进制,还需要二进制…所以就写了现在的脚本

放到path里以后(顺便修改修改了pathext环境变量,加上了.py和.pyw),用起来就简单了

  • iBeyond 九月 9th, 2009 9:38 下午

Python语言: head.py 输出文件开头的8个字节的二进制表示 http://ff.im/-7PHS7

This comment was originally posted on Twitter

发表评论

  • :l
  • :)
  • :q
  • :(
  • :^
  • :x
  • :v
  • :D
  • :s
  • :h
  • :e
  • :X
  • :k
  • :w
  • :d
  • :p

注意:评论中需包含至少一个中文字,否则视为无效

Additional comments powered by BackType