Search code examples
python-3.xbase64decodeencode

Encoding and decoding numpy.array to base64. Why is necessary to use numpy.frombuffer?


Please consider, the following code:

import base64
import numpy as np

array = np.array([1,2]).astype('float32')

arrayencode64 = base64.b64encode(array)

arraydecode64 = base64.b64decode(arrayencode64)

ARRAY = np.frombuffer(arraydecode64, dtype='float32')

print(array)
print()
print(arrayencode64)
print()
print(arraydecode64)
print()
for el in arraydecode64:
    print(el)
print()
print(ARRAY)

Question 1: I would like to understand why, after to apply base64.b64decode, I do not retrieve the original object? I mean, why it need to be read with np.frombuffer with the type specified?

Because, I was expecting to obtain the target object (the numpy.array that is bind in the array variable) just after the application of base64.b64decode.

Question 2: When I print the variable arraydecode64 with the for loop I got a sequence of number. What exactly they mean?

Thanks.


Solution

  • According to the documentation all that base64.b64decode does is take a string and return a byte object. np.frombuffer then takes those bytes and creates and array. base64 doesn't know how numpy represents bytes, and has no idea what an array is.