Terry, Your approach is fine. Personally however I'd just have defined some constants and done a direct bitwise and - this is the approach used in the stat module:
VMASK = 0x14 # 00011000 VER00 = 0x00 VER01 = 0x04 VER10 = 0x10 VER11 = 0x14 version = byte & VMASK if version == VER00: #do something elif version == VER01: # do another etc... But I'm just an old assembler programmer in disguise :-) A function approach is OK too... Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ----- Original Message ----- From: "Terry Carroll" <[EMAIL PROTECTED]> To: <tutor@python.org> Sent: Tuesday, May 16, 2006 6:25 AM Subject: [Tutor] Bit-level field extraction >I want to see if I'm reinventing a wheel here, or maybe doing it > unpythonically. > > I need to extract from a byte (i.e., a one-character string) a field > of an > certain number of bits. For example, a certain byte of an MP3 frame > header has the format xxxVVxxx, where the value of VV (00, 01, 10 or > 11) > tels what version of MPEG Audio is being used. The other bits > marked 'x' > are not relevant to the version id, and may be 1s or 0s. > > Here's my stab: > > def getbits(byte, fieldlength, rightpad): > ''' > returns an integer with the value derived from a string of bits > of > length fieldlength, right-padded with rightpad number of bits. > e.g., getbyte(byte, 2, 3) returns a value from bits 3-4 > (counting from the right) > ''' > bitmask = (2**fieldlength-1) << rightpad > return (ord(byte) & bitmask) >> rightpad > > testbytes = ["\xC0", "\x08", "\xF0", "\x19"] > for byte in testbytes: > print getbits(byte, 2, 3) > # should get 0, 1, 2, 3 > > > This works (at least for these 4 test cases). But is this the best > way to > extract a bit-level field, or am I missing some appropriate module > or > something? > > > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor