views:

77

answers:

2

From the Oracle docs.

A number representing one or more statistics class. The following class numbers are additive:

  1 - User
  2 - Redo
  4 - Enqueue
  8 - Cache
  16 - OS
  32 - Real Application Clusters
  64 - SQL
  128 - Debug

It there a standard solution for taking say 22 and decoding that into 16, 4, and 2? My first guess would be to create an object which holds every possible combination and use that as a lookup? Is there a better solution using binary or something? Preferred solution would by in Python. (disclaimer: This is not homework.)

+4  A: 

Each of those values corresponds to a single bit. So use the binary.

1<<0 - 1 - User
1<<1 - 2 - Redo
1<<2 - 4 - Enqueue
1<<3 - 8 - Cache
1<<4 - 16 - OS
1<<5 - 32 - Real Application Clusters
1<<6 - 64 - SQL
1<<7 - 128 - Debug

Use & to test for each bit.

def decode(value):
    readable = []
    flags = ['User', 'Redo', 'Enqueue', 'Cache', 'OS',
             'Real Application Clusters', 'SQL', 'Debug']
    for i, flag in enumerate(flags):
        if value & (1<<i):
            readable.append(flags[i])
    return readable

print decode(22)
retracile
Also, you should have some variable that make it easier to understand what you're doing, such as (USER_FLAG | flags) or (RAC_FLAG | flags)
Jeremy Powell
In C, I'd agree with you. But in python, use the index into a list for that.
retracile
hughdbrown
+4  A: 

You want to use binary operations to decode the original. The following code actually returns the correct strings:

>>> FLAGS = ('User', 'Redo', 'Enqueue', 'Cache', 'OS',
...          'Real Application Clusters', 'SQL', 'Debug')
>>> def getFlags(value):
...   flags = []
...   for i, flag in enumerate(FLAGS):
...     if value & (1 << i):
...       flags.append(flag)
...   return flags
...
>>> print getFlags(22)
['Redo', 'Enqueue', 'OS']

If you really just want the constants:

>>> def binaryDecomposition(value):
...   return [1 << i for i in xrange(len(FLAGS)) if value & (1 << i)]
...
>>> print binaryDecomposition(22)
[2, 4, 16]
chrispy
hughdbrown