1

In python, I'm trying to convert a string literal to it's hexadecimal 4 byte equivalent. Here's an example of what I'm doing:

import struct
struct.pack("<i", int("08050030", 16))
>>'0\x00\x05\x08'

Why is the output rendering like this? I would expect \x30\x00\x05\x08?

1
  • 3
    because '0' == '\x30'. If the character can be represented as a ascii character, it is displayed as the chracter instead of \xOO form. Commented Dec 8, 2015 at 4:48

1 Answer 1

2

You would probably be surprised if the REPL did this

>>> "hello"
'\x68\x65\x6c\x6c\x6f'

Luckily it doesn't. printable characters are printed as themselves. unprintable characters use shortcuts such as '\n' and when none is available, the last resort is to use the hex notation.

It's perfectly acceptable to use hex encoding anywhere in your literals

>>> '\x30\x00\x05\x08'
'0\x00\x05\x08'

It's just not Python's preference to use them for display.

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.