[Tutor] Bit-level field extraction

Terry Carroll carroll at tjc.com
Tue May 16 20:17:19 CEST 2006


On Tue, 16 May 2006, Alan Gauld wrote:

> 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...

Good idea.  In this particular case, I actualy need the value, because 
it's to be used either as a key to a dictionary or a subscript to a list 
later on; i.e., my if tree would look like this:

  if version == VER00:
     ver_num = 0
  elif version == VER01:
     ver_num = 1
  elif version == VER02:
     ver_num = 2
  elif version == VER03:
     ver_num = 3

Actually, the version number doesn't equal the two-bit number; values of 
0, 2 and 3 mean versions 2.5, 2 or 1, respectively (1 being reserved), but 
you get the idea.  The key is I need later to be able to use the value 
itself.

But I have a number of other parts of the frame header where the defined 
constants are a great way to go; thanks.
  
> But I'm just an old assembler programmer in disguise :-)

Heh, you and me both.  I cut my teeth on IBM System/370 assembler.  Last
time I had a job where I actually did programming as part of it, it was
System/390 machine code.  That's right, machine code, not assembler; I'd 
directly type my hexadecimal programs into low storage at the operator's 
console.




More information about the Tutor mailing list