# [Numpy-discussion] How to handle fields less than one byte in a recarray

Kim Hansen slaunger@gmail....
Thu Jan 15 04:48:23 CST 2009

```Hi Numpy forum

Let me start out with a generic example:

In [3]: test_byte_str = "".join(["\x12\x03", "\x23\x05", "\x35\x08"])

In [4]: desc = dtype({'names' : ["HIGHlow", "HIGH + low"], 'formats': [uint8, ui
nt8]})

In [5]: r = rec.fromstring(test_byte_str, dtype=desc)

In [6]: r[0]
Out[6]: (18, 3)

In [7]: r['HIGHlow']
Out[7]: array([18, 35, 53], dtype=uint8)

In [8]: high = r['HIGHlow'] >> 4

In [9]: high
Out[9]: array([1, 2, 3], dtype=uint8)

In [10]: low = r['HIGHlow'] & 0x0F

In [11]: low
Out[11]: array([2, 3, 5], dtype=uint8)

In [12]: high_plus_low = high + low

In [13]: high_plus_low
Out[13]: array([3, 5, 8], dtype=uint8)

In [14]: r["HIGH + low"]
Out[14]: array([3, 5, 8], dtype=uint8)

So I have here an array, where the first byte actually represents two
fields, HIGH and low, where HIGH are the four most significant bits
and low are the four least significant bits.

As you can see in the example I can figure out how to get an array of
HIGH and low by postprocessing the recordarray, but I would really
like to encapsulate this logic somehow inside the recordarray (or in
an instance of derived class), such that I could access the arrays
directly as

r["HIGH"] and r["low"]

or perhaps even better wrap it all up inside a class RWrapper, such that

r = RWrapper(test_byte_str)
r.low

would work

but not

r.HIGHlow

How do I implment that in a Pythonic way?

My real application is considerebaly more complicated, but I think
this describes the main problem.
```

More information about the Numpy-discussion mailing list