python处理二进制数据的方法

本文实例讲述了python处理二进制数据的方法。分享给大家供大家参考。具体如下:

#!/usr/env/env python
#-*- coding: cp936 -*-
””’
add head infomation for pcm file
”’
import sys
import struct
import os
__author__ = ‘bob_hu, hewitt924@gmail.com’
__date__ = ‘dec 19,2011’
__update__ = ‘dec 19,2011′
def geneheadinfo(samplerate,bits,samplenum):
””’
生成头信息,需要采样率,每个采样的位数,和整个wav的采样的字节数
”’
rheadinfo = ‘\x52\x49\x46\x46’
filelength = struct.pack(‘i’,samplenum + 36)
rheadinfo += filelength
rheadinfo += ‘\x57\x41\x56\x45\x66\x6d\x74\x20\x10\x00\x00\x00\x01\x00\x01\x00’
rheadinfo += struct.pack(‘i’,samplerate)
rheadinfo += struct.pack(‘i’,samplerate * bits / 8)
rheadinfo += ‘\x02\x00’
rheadinfo += struct.pack(‘h’,bits)
rheadinfo += ‘\x64\x61\x74\x61’
rheadinfo += struct.pack(‘i’,samplenum)
return rheadinfo
if __name__ == ‘__main__’:
if len(sys.argv) != 5:
print “usage: python %s infile samplerate bits outfile” % sys.argv[0]
sys.exit(1)
fout = open(sys.argv[4],’wb’) #用二进制的写入模式
#fout.write(struct.pack(‘4s’,’\x66\x6d\x74\x20′))
#写入一个长度为4的串,这个串的二进制内容为 66 6d 74 20
#riff_flag,afd,fad,afdd, = struct.unpack(‘4c’,fin.read(4))
#读入四个字节,每一个都解析成一个字母
#open(sys.argv[4],’wb’).write(struct.pack(‘4s’,’fmt ‘))
#将字符串解析成二进制后再写入
#open(sys.argv[4],’wb’).write(‘\x3c\x9c\x00\x00\x57’)
#直接写入二进制内容:3c 9c 00 00 57
#fout.write(struct.pack(‘i’,6000)) #写入6000的二进制形式
#check whether infile has head-info
fin = open(sys.argv[1],’rb’)
riff_flag, = struct.unpack(‘4s’,fin.read(4))
if riff_flag == ‘riff’:
print “%s 有头信息” % sys.argv[1]
fin.close()
sys.exit(0)
else:
print “%s 没有头信息” % sys.argv[1]
fin.close()
#采样率
samplerate = int(sys.argv[2])
#bit位
bits = int(sys.argv[3])
fin = open(sys.argv[1],’rb’)
startpos = fin.tell()
fin.seek(0,os.seek_end)
endpos = fin.tell()
samplenum = (endpos – startpos)
print samplenum
headinfo = geneheadinfo(samplerate,bits,samplenum)
fout.write(headinfo)
fin.seek(os.seek_set)
fout.write(fin.read())
fin.close()
fout.close()

希望本文所述对大家的python程序设计有所帮助。

Posted in 未分类

发表评论