How to get the raw bytes from a hex string in python

1.7k views Asked by At

I have the following problem in python

I have the value 0x402de4a in hex and would like to convert it to bytes so I use .to_bytes(3, 'little') which gives me b'J\2d@' if I print it. I am aware that this is just a representation of the bytes but I need to turn a string later for the output which would give me J\2d@ if I use str() nut I need it to be \x4a\x2d\x40 how can I convert the byte object to string so I can get the raw binary data as a string

my code is as follows

addr = 0x402d4a
addr = int(addr,16)

addr = str(addr.to_bytes(3,'little'))
print(addr)

and my expected output is \x4a\x2d\x40

Thanks in advance

1

There are 1 answers

0
pepoluan On

There is no direct way to get \x4a\x2d and so forth from a string. Or bytes, for this matter.

What you should do:

  1. Convert the int to bytes -- you've done this, good
  2. Loop over the bytes, use f-string to print the hexadecimal value with the "\\x" prefix
  3. join() them

2 & 3 can nicely be folded into one generator comprehension, e.g.:

rslt = "".join(
    f"\\x{b:02x}" for b in value_as_bytes
)