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

nad34
  • 343
  • 4
  • 13
  • 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()`. – Kemp Dec 04 '20 at 14:57
  • In terms of the actual question, this has been asked a number of times on Stack Overflow, for example at https://stackoverflow.com/questions/25348229/forcing-escaping-of-printable-characters-when-printing-bytes-in-python-3 and https://stackoverflow.com/questions/26568245/show-hex-value-for-all-bytes-even-when-ascii-characters-are-present. It may be worth looking through previous answers. – Kemp Dec 04 '20 at 15:01
  • Thanks, but when I use `addr.to_bytes(3,'little').decode()` I get J\x1e – nad34 Dec 04 '20 at 15:04
  • 1
    Does this answer your question? [Forcing escaping of printable characters when printing bytes in Python 3](https://stackoverflow.com/questions/25348229/forcing-escaping-of-printable-characters-when-printing-bytes-in-python-3) – Kemp Dec 04 '20 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` – pepoluan Dec 04 '20 at 15:10

1 Answers1

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
)
pepoluan
  • 6,132
  • 4
  • 46
  • 76