Customizing struct printing

51 views
Skip to first unread message

capr...@gmail.com

unread,
Feb 3, 2016, 12:18:19 PM2/3/16
to Construct
I am using Struct to consume a binary file containing raw sensor data. The data is a series of 16-bit values. If the data contains an ASCII code such as 0x63 it prints as the ASCII letter 'c'. The letter 'c' means nothing to me when I'm browsing my sensor data. How can I force this data to print in hex notation?

Here is what happens using the normal print built-in:

>>> from construct import *
>>> data = "\x01\x02\x63\x64"
>>> s = Struct("s", Field("val1",2), Field("val2",2))
>>> print s.parse(data)
Container:
    val1
= '\x01\x02'
    val2
= 'cd'


The output I would like is something like:

>>> print s.parse(data)
Container:
    val1
= 0x0102
    val2
= 0x6364


Any clever ideas on how to do this? Thanks!

p.s
The monkey-wrench thrown in is that this example simplifies my Struct greatly. I have other data in this struct that isn't sensor data (timestamp, etc) and I am happy with how that prints out by default. For example, a timestamp of ("12:30:05") would not be useful to view as 0x313233303035.

capr...@gmail.com

unread,
Feb 3, 2016, 12:20:58 PM2/3/16
to Construct
My best idea so far has been to make a new class "HexField" that inherits from "Field" (really, StaticField) and then override the __str__() method. This didn't work. However Construct is printing containers does not use the __str__() method as I suspected.

Steven Michalske

unread,
Feb 4, 2016, 6:01:20 AM2/4/16
to const...@googlegroups.com

On Feb 3, 2016, at 9:18 AM, capr...@gmail.com wrote:

s = Struct("s", Field("val1",2), Field("val2",2))

Why are you not using?
s = Struct("s", UBInt16('val1'), UBInt16('val2'))
print(s.parse(data))
Container:
    val1 = 258
    val2 = 25444
Do you need byte strings of data, from the Field?

As for your monkey patch for printing it looks like you need to override __pretty_str__ of the returned value from parsing code of the StaticField or MetaField classes.


Arek Bulski

unread,
Sep 26, 2016, 10:45:02 AM9/26/16
to Construct
Field does no longer exist. Either use Bytes or BytesInteger, one works with bytes other with ints. As for printing integers in hexadecimal mode, either look at HexDump which right now works with bytes only or ask a feature request for a wrapper that works with integers as well. 
Reply all
Reply to author
Forward
0 new messages