14

This is my first code in python and I have this issue:

I'm reading a binary file as:

def read_file(file):
    with open(file, "rb") as f:
        frame = f.read()
        print(type(frame)) #out = <class 'bytes'>
        return frame

I need to convert all the vector to int values instead using them as bytes.

After printing I get something like this:

print(frame[0:10])
b'\xff\xff\xff\xffXabccc'

However if I print passing one position only I get this:(the integer values are correct, but I just get them using the function print)

print(frame[0])
255    
print(frame[1])
255
print(frame[2])
255
print(frame[3])
255
print(frame[4])
88
print(frame[5])
97
print(frame[6])
98
print(frame[7])
99
print(frame[8])
99
print(frame[9])
99
print(frame[10])
98

The question is: How can I convert all the positions of my array in one step? I would like to run the code

print(frame[0:10])

and get something like

[255, 255, 255, 255, 88, 97, 98, 99 ,99, 99, 98]
1
  • 1
    FWIW, frame is not a bytearray, but a bytes object. Both exist in Python, but whereas the former is mutable, your bytes object is not.
    – JohanL
    Commented Feb 26, 2018 at 13:41

4 Answers 4

29

Note: this solution only works for Python 3. For Python 2 solution please see Scott Hunter's answer.

You could do this using a list comprehension:

In [1]: frame = b'\xff\xff\xff\xffXabccc'

In [2]: int_values = [x for x in frame]

In [3]: print(int_values)
[255, 255, 255, 255, 88, 97, 98, 99, 99, 99]

To confirm that these are indeed stored as integer values which you can work with:

In [4]: print([type(x) for x in int_values])
[<class 'int'>, <class 'int'>, <class 'int'>, <class 'int'>, <class 'int'>, 
<class 'int'>, <class 'int'>, <class 'int'>, <class 'int'>, <class 'int'>]
1
  • 2
    Note: only works in Python 3 (Python 2 gives list of characters).
    – glibdud
    Commented Feb 26, 2018 at 13:55
15

The simplest, and most obvious way to do it, is to pass the frame object to the list constructor. No list comprehension is needed for this:

>>> frame = b'\xff\xff\xff\xffXabccc'
>>> list(frame)
[255, 255, 255, 255, 88, 97, 98, 99, 99, 99]
1
  • Note: only works in Python 3 (Python 2 gives list of characters).
    – glibdud
    Commented Feb 26, 2018 at 13:56
3

One solution for python2 or 3 is:

list(bytearray(frame))
2

If you want to use a list of integer values, and not just print them, you could use:

[ord(x) for x in frame]
1
  • 2
    Note: only works in Python 2 (Python 3 throws TypeError).
    – glibdud
    Commented Feb 26, 2018 at 13:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.