Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert bytes in a string back to bytes

Tags:

I understand that there are similar questions, but I do not understand them so here goes: I have bytes (encoded from a string) in a string form (read from a file). When I try to decode the bytes, I get an error saying that it is a string, not bytes. I understand it is in the wrong form, but do I not have the correct information? How can I convert bytes in a string back to bytes? I will also note I know this is not a secure password method and will not be used as one. (I am using python 3)

I've done some research into how I can fix this, but I am very new and either did not understand it or could not apply it. I though this would work but it does not:

password=bytes(password, 'cp037')

Oh well. Here is a short version of the code I have:

#writing to the file
password="example" 
password=password.encode('cp037') 
password=str(password)
f=open("passwordFile.txt", "w+")
f.write(password)
f.close

#reading from the file
f=open("passwordFile.txt","r")
password=f.read()
#this is where I need to turn password back into bytes
password=password.decode('cp037') 
print(password)

I expected to get example as output, but have a error: AttributeError: 'str' object has no attribute 'decode'

like image 309
thinkCode Avatar asked Nov 06 '19 14:11

thinkCode


2 Answers

A quick possibility to convert from a string representation of bytes literals

"b'\x85\xa7\x81\x94\x97\x93\x85'"

to the actual bytes would be

bytes_as_bytes = eval(bytes_literals_as_str)

i.e.

bytes_as_bytes = eval("b'\\x85\\xa7\\x81\\x94\\x97\\x93\\x85'")
like image 192
jotelha Avatar answered Sep 25 '22 19:09

jotelha


write byte, read byte and convert into string using decode

#writing to the file
password="example"
password=password.encode('cp037')
#password=str(password) (remove this line)
f=open("passwordFile.txt", "wb")
f.write(password)
f.close()

#reading from the file
f=open("passwordFile.txt","rb")
password=f.read()
#this is where I need to turn password back into bytes
y=password.decode('cp037')
print(y)
like image 27
Venkatesh Nandigama Avatar answered Sep 25 '22 19:09

Venkatesh Nandigama