Reputation: 535
I have a function to convert bytearrays into bytes:
def dehex(d):
return bytes(bytearray(d))
test = dehex([0xe7,0xcd,0xb0,0xa2])
this works perfectly fine
However
I have a few saved bytearrays like the one above inside a txt file using pickle, that looks like this:
0xe7,0xcd,0xb0,0xa2
and i want to be able to load them from the txt file, the problem arises if i read the file it returns a string which doesn't work with my dehex function. it is like it gets interpreted as such:
dehex(["0xe7,0xcd,0xb0,0xa2"])
how would i make this work?
Upvotes: 0
Views: 185
Reputation: 3722
Perhaps this will help:
my_str = "0xe7,0xcd,0xb0,0xa2" # String read from file.
my_bytes_list = [bytes.fromhex(c[2:]) for c in my_str.split(",")]
result = [dehex(bytes.fromhex(c[2:])) for c in my_str.split(",")]
print (result)
Output:
[b'\xe7', b'\xcd', b'\xb0', b'\xa2']
Upvotes: 1