This article describes how to process binary data in python and how to operate on binary data in Python. For more information, see the following example. Share it with you for your reference. The details are as follows:
#! /Usr/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 ): ''''' generate the header information. sampling rate is required. the number of digits of each sampling, and the number of bytes sampled for the whole wav ''' rHeadInfo = '\ x52 \ x49 \ x46 \ x46' fileLength = struct. pack ('I', sampleNum + 36) rHeadInfo + = fileLen Export 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 ') # use the binary write mode # fout. write (struct. pack ('4s ',' \ x66 \ x6D \ x74 \ x20') # write a string with a length of 4. the binary content of this string is 66 6D 74 20 # Riff_flag, afd, fad, afdd, = struct. unpack ('4c ', fin. read (4) # read four bytes, each parsed into a Letter # open (sys. argv [4], 'WB '). write (struct. pack ('4s ', 'fmt') # parses the string into binary and then writes it to # open (sys. argv [4], 'WB '). write ('\ x3C \ x9C \ x00 \ x00 \ x57') # write binary data directly: 3C 9C 00 00 57 # fout. write (struct. pack ('I', 6000) # write the binary form of 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 header information" % sys. argv [1] fin. close () sys. exit (0) else: print "% s no header information" % 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 ()
I hope this article will help you with Python programming.