NumPy: Convert the raw data in an array to a binary string and then create an array
Raw Array to Binary String/Back
Write a NumPy program to convert raw array data to a binary string and create an array.
Sample Solution:
Python Code:
Sample Output:
Original array: [ 10. 20. 30.] Binary string array: b'\x00\x00\x00\x00\x00\x00$@\x00\x00\x00\x00\x00\x004@\x00\x00\x00\x00\x00\x00>@' Array using fromstring(): [ 10. 20. 30.]
Explanation:
In the above code –
x = np.array([10, 20, 30], float): Create a NumPy array 'x' with the elements 10, 20, and 30 of float data type.
s = x.tostring(): This line converts the NumPy array 'x' to a binary string 's' using the 'tostring()' method. Note that since NumPy 1.9, the preferred method is 'tobytes()' instead of 'tostring()'.
y = np.fromstring(s): Create a new NumPy array 'y' from the binary string 's' using the 'np.fromstring()' function. The new array 'y' will have the same elements as the original array 'x'.
For more Practice: Solve these Related Problems:
- Write a NumPy program to convert an array to a binary string using the tobytes() method and then reconstruct it with frombuffer.
- Create a function that converts an array into a binary representation and then decodes it back into an array.
- Test the conversion on arrays with different data types to ensure that the binary data is correctly interpreted.
- Compare the outputs of np.ndarray.tobytes() with a manual binary conversion method for consistency.
Go to:
PREV : Print All Array Values
NEXT : Sum/Product of Array Elements
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.