0

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?

1 Answer 1

1

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']
Sign up to request clarification or add additional context in comments.

4 Comments

@EmilB Your function is called in the third line
this doesnt work, maybe i if i could turn it into a string somehow
Could you please elaborate? What needs to be turned into string? Also, could you please mention some exact expected output along with the corresponding input, passed to the function. Right now, in my answer, the string 'e7' is being passed to dehex to get the bytes value b'\xe', 'cd' is passed to get b'\xcd', 'b0' is passed to get b'\xb0', and finally, the string 'az' is passed to get the bytes value b'\xaz'. If this is not what is expected, please specify the exact output expected.
Nevermind i got it working, thank you for your advice

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.