SARose
SARose

Reputation: 3725

Bytes to string to bytes. Python 3

This is a simple question but I cannot seem to figure it out. I want to take the bytes outputted from a pickle.dumps() and convert it str and be able to convert it back to bytes compatible such that pickle.loads(string_thing) can recover the original object.

encoded = pickle.dumps(None)
string_encoded = to_string(encoded)
decoded = pickle.loads(safe_decoder(string_encoded))

I know one of the objections are going to be, "why do you need to do this?" Restrictions on allowed types.

Upvotes: 1

Views: 159

Answers (1)

Ralf
Ralf

Reputation: 16505

@deceze gives a good idea: use the module base64 with its functions .b64encode() and .b64decode().

Here is an example:

>>> 'Álñó@'
'Álñó@'
>>> 'Álñó@'.encode()
b'\xc3\x81l\xc3\xb1\xc3\xb3@'
>>> base64.b64encode('Álñó@'.encode())
b'w4Fsw7HDs0A='
>>> base64.b64encode('Álñó@'.encode()).decode()
'w4Fsw7HDs0A='

Now you have a string in base64. For the reverse process:

>>> base64.b64encode('Álñó@'.encode()).decode().encode()
b'w4Fsw7HDs0A='
>>> base64.b64decode(base64.b64encode('Álñó@'.encode()).decode().encode())
b'\xc3\x81l\xc3\xb1\xc3\xb3@'
>>> base64.b64decode(base64.b64encode('Álñó@'.encode()).decode().encode()).decode()
'Álñó@'

Would that work for you?


Example using pickle:

>>> original_obj = 456.5
>>> original_obj
456.5
>>> type(original_obj)
<class 'float'>
>>> intermediate_str = base64.b64encode(pickle.dumps(original_obj)).decode()
>>> intermediate_str
'gANHQHyIAAAAAAAu'

>>> new_obj = pickle.loads(base64.b64decode(intermediate_str.encode()))
>>> new_obj
456.5
>>> type(new_obj)
<class 'float'>

>>> original_obj == new_obj
True

Upvotes: 2

Related Questions