Escapes???
Darrell Gallion
darrell at dorb.com
Sat Jun 3 02:32:38 EDT 2000
Bug fixes :)
hexData1='''
0016 4210 0100 0004 0000 0101 c042 0100
0242 0500 000f
'''
hexData2='''
0x0016 0x4210 0x0100 0x0004 0x0000 0x0101 0xc042 0x0100
0x0242 0x0500 0x000f
'''
hexData3=r'''
\x0016 \x4210 \x0100 \x0004 \x0000 \x0101 \xc042 \x0100
\x0242 \x0500 \x000f
'''
hexData4=r'''
\x00\x16 \x42\x10 \x01\x00 \x00\x04 \x00\x00 \x01\x01 \xc0\x42 \x01\x00
\x02\x42 \x05\x00 \x00\x0f
'''
hexData5=r'''
0x0016 \x42\x10 0100 \x0004 \x00\x00 \x01\x01 \xc0\x42 \x01\x00
\x02\x42 \x05\x00 \x00\x0f
'''
import re, string, struct
bigEndian={1:"c", 2:"c", 3:">h", 4:">h", 5:">l", 6:">l"}
def binConvert(s, sizeMap={1:"c", 2:"c", 3:"h", 4:"h", 5:"l", 6:"l"}):
"""
Convert s to binary
s can be formated like:
0xabcd \x11 \x9999 abcd
sizeMap maps the size of each number to a struct format string
for it's conversion. bigEndian was used for regression so that
r"\x00\x16" == r"\x0016"
"""
res=[]
temp = re.findall(r"(?i)[^ \\x\n\t]+(?!x)",s)
fmt=sizeMap[len(temp[0])]
lastLen=len(temp[0])
for v in temp:
if len(v) != lastLen:
lastLen=len(v)
fmt=sizeMap[lastLen]
if fmt != 'c':
res.append(struct.pack(fmt, eval("0x"+v)))
else:
res.append(struct.pack(fmt, eval(r'"\x%s"'%v)))
return string.join(res,'')
def hexConvert(s, size=1, outPutStyle="0x%s "):
"""
Convert binary string s to a hex format
size ==> how large should each hex value be
outPutStyle ==> how should each value be formated
"""
res=[]
while s:
temp=s[:size]
s=s[size:]
l=[]
for i in temp:
l.append("%x"%ord(i))
val=string.join(l,'')
res.append(outPutStyle%val)
return string.join(res,'')
def regress(show=0):
lastB=None
for k,v in globals().items():
if re.match("hexData", k):
print 'Testing:', k
b=binConvert(v, bigEndian)
h=hexConvert(b)
if show:
print b
print h
print '-'*50
assert(b==binConvert(h, bigEndian))
if lastB:
assert(b==lastB)
lastB=b
else:
lastB=b
regress(1)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20000602/5d2a8330/attachment.html>
More information about the Python-list
mailing list