| prev | Draft Version 546 (Mon Dec 5 17:01:30 2005) | next |
"10239472" is 8 bytes long"False" is 5 bytes, 0 is one bit (40:1)"34" to the one represented by "57"# hex binary
MERCURY = 0x01 # 0001
PHOSPHORUS = 0x02 # 0010
CHLORINE = 0x04 # 0100
# Sample contains mercury and chlorine
sample = MERCURY | CHLORINE
print 'sample: %04x' % sample
# Check for various elements
for (flag, name) in [[MERCURY, "mercury"],
[PHOSPHORUS, "phosphorus"],
[CHLORINE, "chlorine"]]:
if sample & flag:
print 'sample contains', name
else:
print 'sample does not contain', name
sample: 0005 sample contains mercury sample does not contain phosphorus sample contains chlorine
x to 1:
mask in which bit i is 1 and all others are 0x = x | maskx to 0:
mask in which bit i is 1 and all others are 0~, so that the ith bit is 0, and all the others are 1x = x & maskx << N
f.read(N) reads (up to) next N bytesNonef.write(str) writes the bytes in the string strinput = open(filename, 'rb') (and similarly for output)"\r\n" to Unix-style "\n"…"r", then in "rb"
import sys
print sys.platform
for mode in ('r', 'rb'):
f = open('open_binary.py', mode)
s = f.read(40)
f.close()
print repr(s)
linux2 'import sys\nprint sys.platform\nfor mode i' 'import sys\nprint sys.platform\nfor mode i'
fwrite(&array, sizeof(int), 3, file) will write 3 4-byte integers from address array to filestruct module to pack and unpackpack(fmt, v1, v2, …) packs the values v1, v2, etc. according to fmt, returning a stringunpack(fmt, str) unpacks the values in str according to fmt, returning a tuplecalcsize(fmt) calculates how large (in bytes) the data produced using fmt will be"4i" is four integers"4s" for a 4-character stringunpack know how much data to use?"B" or "h" instead of the full 32import struct fmt = 'hh' # two 16-bit integers x = 31 y = 65 binary = struct.pack(fmt, x, y) print 'binary representation:', repr(binary) normal = struct.unpack(fmt, binary) print 'back to normal:', normal
binary representation: '\x1f\x00A\x00' back to normal: (31, 65)
'\x1f\x00A\x00'?['\x1f', '\x00', 'A', '\x00']
"A" is 6510import struct
packed = struct.pack('4c', 'a', 'b', 'c', 'd')
print 'packed string:', repr(packed)
left16, right16 = struct.unpack('hh', packed)
print 'as two 16-bit integers:', left16, right16
all32 = struct.unpack('i', packed)
print 'as a single 32-bit integer', all32[0]
float32 = struct.unpack('f', packed)
print 'as a 32-bit float', float32[0]
packed string: 'abcd' as two 16-bit integers: 25185 25699 as a single 32-bit integer 1684234849 as a 32-bit float 1.67779994081e+22
def packVec(vec):
buf = struct.pack('i', len(vec))
for v in vec:
buf += struct.pack('i', v)
return buf
calcsize('i') instead of hard-coding the number 4def unpackVec(buf):
# Get the count of the number of elements in the vector.
intSize = struct.calcsize('i')
count = struct.unpack('i', buf[0:intSize])[0]
# Get 'count' values, one by one.
pos = intSize
result = []
for i in range(count):
v = struct.unpack('i', buf[pos:pos+intSize])
result.append(v[0])
pos += intSize
return result
if __name__ == '__main__':
tests = [
[],
[1],
[1, 2],
[-3, 456, 7890]
]
for t in tests:
s = packVec(t)
v = unpackVec(s)
assert v == t
import struct
def packStrings(strings):
result = ''
for s in strings:
length = len(s)
format = 'i%ds' % length
result += struct.pack(format, length, s)
return result
def unpackStrings(buf):
intSize = struct.calcsize('i')
pos = 0
result = []
while pos < len(buf):
length = struct.unpack('i', buf[pos:pos+intSize])[0]
pos += intSize
format = '%ds' % length
s = struct.unpack(format, buf[pos:pos+length])[0]
pos += length
result.append(s)
return result
if __name__ == '__main__':
tests = ['', 'a', 'bcd']
for i in range(len(tests)):
t = tests[0:i+1]
buffer = packStrings(t)
result = unpackStrings(buffer)
assert result == t
def store(outstream, format, data):
'''Store records in a file. Each record is either a list or a
tuple; all records must have exactly the same format.'''
# Length of metadata.
s = struct.pack("i", len(format))
outstream.write(s)
# Metadata.
outstream.write(format)
# Records.
for d in data:
d = [format] + list(d) # Build pack's argument list
s = struct.pack(*d) # Apply pack to those arguments
outstream.write(s)
struct.pack is calledstruct.pack to itstore
def retrieve(instream):
'''Retrieve records from a file whose format is:
'i' : length of metadata
metadata : record format descriptor
records : actual data'''
# Length of metadata.
numBytes = struct.calcsize("i")
s = instream.read(numBytes)
formatLen = struct.unpack("i", s)[0]
# Metadata.
format = instream.read(formatLen)
recordLen = struct.calcsize(format)
# Records.
data = []
s = instream.read(recordLen)
while s:
assert len(s) == recordLen
d = list(struct.unpack(format, s))
data.append(d)
s = instream.read(recordLen)
# Done
return data
assert in the reading loopif __name__ == '__main__':
from cStringIO import StringIO
tests = [
['i', [[1]]],
['i', [[1], [2]]],
['3s', [['xyz']]],
['3s', [['abc'], ['def']]],
['f3s', [[1.0, 'pqr']]],
['f3s', [[2.0, 'stu'], [3.0, 'vwx']]]
]
for (format, data) in tests:
outstream = StringIO()
store(outstream, format, data)
instream = StringIO(outstream.getvalue())
dup = retrieve(instream)
assert data == dup
| prev | Copyright © 2005, Python Software Foundation. See License for details. | next |