K
Kamilche
I'm trying to pack two characters into a single byte, and the shifting
in Python has me confused.
Essentially, it should be possible to use a 'packed string' format in
Python, where as long as the characters you're sending are in the ASCII
range 0 to 127, two will fit in a byte.
Here's the code. Can you tell what I'm doing wrong?
|import types
|
|def PackString(s):
| if type(s) != types.StringType:
| raise Exception("This routine only packs strings!")
| l = len(s)
| if l % 2 != 0:
| s = s + '\0'
| l += 1
| chars = []
| for i in range(0, l, 2):
| x = ord(s)
| y = ord(s[i+1])
| chars.append(chr((y << 1) | x))
| return ''.join(chars)
|
|def UnpackString(s):
| if type(s) != types.StringType:
| raise Exception("This routine only unpacks strings!")
| l = len(s)
| chars = []
| for i in range(l):
| temp = ord(s)
| c = 0xf0 & temp
| chars.append(chr(c))
| c = 0x0f & temp
| chars.append(chr(c))
| return ''.join(chars)
|
|
|def main():
| s = "Test string"
| print s
| packed = PackString(s)
| print "This is the string packed:"
| print packed
| print "This is the string unpacked:"
| print UnpackString(packed)
|
|main()
in Python has me confused.
Essentially, it should be possible to use a 'packed string' format in
Python, where as long as the characters you're sending are in the ASCII
range 0 to 127, two will fit in a byte.
Here's the code. Can you tell what I'm doing wrong?
|import types
|
|def PackString(s):
| if type(s) != types.StringType:
| raise Exception("This routine only packs strings!")
| l = len(s)
| if l % 2 != 0:
| s = s + '\0'
| l += 1
| chars = []
| for i in range(0, l, 2):
| x = ord(s)
| y = ord(s[i+1])
| chars.append(chr((y << 1) | x))
| return ''.join(chars)
|
|def UnpackString(s):
| if type(s) != types.StringType:
| raise Exception("This routine only unpacks strings!")
| l = len(s)
| chars = []
| for i in range(l):
| temp = ord(s)
| c = 0xf0 & temp
| chars.append(chr(c))
| c = 0x0f & temp
| chars.append(chr(c))
| return ''.join(chars)
|
|
|def main():
| s = "Test string"
| print s
| packed = PackString(s)
| print "This is the string packed:"
| print packed
| print "This is the string unpacked:"
| print UnpackString(packed)
|
|main()