pythonpython-2.7pyasn1

pyasn1 prettyPrint() - display integers in hex


I have many univ.Integer(), but would like to print all of them in hex, which are easy to related to the decoding of substrate.

How can I do it ?

one such example is

namedtype.NamedType('vendor-id', univ.Integer())
namedtype.NamedType('device-id', univ.Integer())
namedtype.NamedType('subven-id', univ.Integer())
namedtype.NamedType('subsys-id', univ.Integer())

any options to pretty print, which will convert all integer to hex ? or subcalss the univ.Integer for some display tricks ?


Solution

  • There is no option to prettyPrint like that. I can offer you two thoughts, though.

    If you need to pretty-print specific integers, rather than a tree whole composite objects with embedded Integers, you could just use hex():

    >>> Integer(123).prettyPrint()
    '123'
    >>> hex(int(Integer(123)))
    '0x7b'
    

    Otherwise you could amend pyasn1 Integer.prettyOut() method like this:

    >>> class MyInteger(Integer):
    ...     def prettyOut(self, value):
    ...         return hex(value)
    ... 
    >>> MyInteger(123).prettyPrint()
    '0x7b'
    >>>