[Tutor] back on bytes

Alan Gauld alan.gauld at btinternet.com
Sat Jul 7 10:07:53 CEST 2007


"Terry Carroll" <carroll at tjc.com> wrote

>> In your formula ( (176 & 127) * 256 + 192 ) you're only using 7 
>> bits
>> of your high byte.  Why are you masking off that last bit?
> ....
> Scrounging through some old code, I used to use this to pull out the
> length:
>
> def ID3TagLength(s):
>    """
>    Given a 4-byte string s, decode as ID3 tag length
>    """
>    return (ord(s[0]) * 0x200000 +
>            ord(s[1]) *   0x4000 +
>            ord(s[2]) *     0x80 +
>            ord(s[3]) )

I'm intrigued as to why people are using weird combinations
of math to manipulate bitstrings given that Python has a full
set of bitwise operators. Surely it is easier and more obvious
to simply shift the bits right or left using >> and << and use
bitwise and/or operations than do all this multiplication and
addition malarky. (Its also a lot faster!) If you are going to
operate at the bit level why not use the bit level operations?

Curious.

Alan G. 




More information about the Tutor mailing list