On 23 Feb 2005 22:06:54 -0800, "Kamilche" <[EMAIL PROTECTED]> wrote:
>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. It should be possible, but only in a realm where phlogiston and perpetual motion machines exist. To hold one ASCII character 0 <= ord(c) < 128, you need log2(128) == 7 bits. There are 8 bits in a byte. Therefore you can hold only 8/7.0 == 1.14... ASCII characters in a standard 8-bit byte. If there is such a thing as a 14-bit byte, that's news to me. Other things you are doing wrong: 1. Using "L".lower() as a variable name. Some fonts make it extremely hard to work out what is what in "l1l1l1l1l1l1ll1l1l" -- can you read that??? 2. Hmmm: >>> "chr((y << 1) | x))".upper() 'CHR((Y << 1) | X))' OK so that's a one, not the length of your string, as augmented. Either would be be wrong. Shifting a character left ONE bit (or, changing the emphasis, one BIT) and then ORing in another character would be vaguely reasonable only if you were writing a hash function. 3. Supposing this modern alchemy had worked: when unpacking, how would you know whether the string was originally (say) seven characters long or 8 characters long? 4. Your unpacking routine appears to be trying to unpack two 4-bit items (nibbles) out of a byte, but is not doing (temp & 0xf0) >> 4 for the top nibble as one might expect ..... aaahhh!!?? are you trying to emulate packed decimal??? 5. Not writing down a clear statement of what you are trying to do, followed by examples of input and expected output. This latter goes by fancy names like "test-driven development"; when I started programming it was known as "common sense". 6. Not using Python interactively to explore what's going on: >>> ord('x') 120 >>> ord('y') 121 >>> (120 << 1) 240 >>> (120 << 1) | 121 249 >>> HTH, John -- http://mail.python.org/mailman/listinfo/python-list