1

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

5
  • A problem you will encounter is that str(addr.to_bytes(3,'little')) doesn't quite do what you think it does. You likely want addr.to_bytes(3,'little').decode(). Commented Dec 4, 2020 at 14:57
  • In terms of the actual question, this has been asked a number of times on Stack Overflow, for example at stackoverflow.com/questions/25348229/… and stackoverflow.com/questions/26568245/…. It may be worth looking through previous answers. Commented Dec 4, 2020 at 15:01
  • Thanks, but when I use addr.to_bytes(3,'little').decode() I get J\x1e Commented Dec 4, 2020 at 15:04
  • 1
    Does this answer your question? Forcing escaping of printable characters when printing bytes in Python 3 Commented Dec 4, 2020 at 15:07
  • There is no point doing int(..., 16) in your example. Python already understand that 0x402d4a is base-16, and performed the conversion to int implicitly. In fact, doing what you did there will raise a TypeError Commented Dec 4, 2020 at 15:10

1 Answer 1

1

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

Comments

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.