List of integers

Chris Angelico rosuav at gmail.com
Sun Dec 13 19:32:58 EST 2015


On Mon, Dec 14, 2015 at 11:24 AM, KP <kai.peters at gmail.com> wrote:
> data = list(f.read(4))
> print data
>
> from a binary file might give
>
> ['\x10', '\x20', '\x12', '\x01']
>
>
> How can I receive this instead?
>
> [0x10, 0x20, 0x12, 0x01]
>
> Thanks for all help!

Try this:

data = [ord(x) for x in f.read(4)]

Note that it won't print out in hexadecimal.

>>> [0x10, 0x20, 0x12, 0x01]
[16, 32, 18, 1]

If you insist on that, try a subclass of int:

class ord(int):
    ord = ord
    def __new__(cls, x):
        return super().__new__(cls, cls.ord(x))
    def __repr__(self): return hex(self)

Then they'll come out in hex.

ChrisA



More information about the Python-list mailing list