Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert python byte "array" to int "array

Tags:

python

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]
like image 844
Eduardo Nunes dos Santos Avatar asked Feb 26 '18 12:02

Eduardo Nunes dos Santos


People also ask

Can you convert a byte to an int?

To convert bytes to int in Python, use the int. from_bytes() method. A byte value can be interchanged to an int value using the int. from_bytes() function.

What is Python Bytearray?

The Python bytearray() function converts strings or collections of integers into a mutable sequence of bytes. It provides developers the usual methods Python affords to both mutable and byte data types. Python's bytearray() built-in allows for high-efficiency manipulation of data in several common situations.

Is byte array immutable in Python?

bytearray() Syntax bytearray() method returns a bytearray object (i.e. array of bytes) which is mutable (can be modified) sequence of integers in the range 0 <= x < 256 . If you want the immutable version, use the bytes() method.


1 Answers

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'>]
like image 109
sjw Avatar answered Oct 03 '22 10:10

sjw