27

I'm trying to find a way to print a string in hexadecimal. For example, I have this string which I then convert to its hexadecimal value.

my_string = "deadbeef"
my_hex = my_string.decode('hex')

How can I print my_hex as 0xde 0xad 0xbe 0xef?

To make my question clear... Let's say I have some data like 0x01, 0x02, 0x03, 0x04 stored in a variable. Now I need to print it in hexadecimal so that I can read it. I guess I am looking for a Python equivalent of printf("%02x", my_hex). I know there is print '{0:x}'.format(), but that won't work with my_hex and it also won't pad with zeroes.

1

7 Answers 7

33

You mean you have a string of bytes in my_hex which you want to print out as hex numbers, right? E.g., let's take your example:

>>> my_string = "deadbeef"
>>> my_hex = my_string.decode('hex')  # python 2 only
>>> print my_hex
Þ ­ ¾ ï

This construction only works on Python 2; but you could write the same string as a literal, in either Python 2 or Python 3, like this:

my_hex = "\xde\xad\xbe\xef"

So, to the answer. Here's one way to print the bytes as hex integers:

>>> print " ".join(hex(ord(n)) for n in my_hex)
0xde 0xad 0xbe 0xef

The comprehension breaks the string into bytes, ord() converts each byte to the corresponding integer, and hex() formats each integer in the from 0x##. Then we add spaces in between.

Bonus: If you use this method with unicode strings (or Python 3 strings), the comprehension will give you unicode characters (not bytes), and you'll get the appropriate hex values even if they're larger than two digits.

Addendum: Byte strings

In Python 3 it is more likely you'll want to do this with a byte string; in that case, the comprehension already returns ints, so you have to leave out the ord() part and simply call hex() on them:

>>> my_hex = b'\xde\xad\xbe\xef'
>>> print(" ".join(hex(n) for n in my_hex))
0xde 0xad 0xbe 0xef
Sign up to request clarification or add additional context in comments.

3 Comments

Just to note this won't work on Python 3.x, while the unhexlifysolution will...
@alexis the .decode as str no longer has a decode as it's not necessary.... and b'deadbeef'.decode('hex') won't work as hex encoding has been removed
But that's just how the OP constructed the string: It's not part of the answer. hex(ord(c)) will still convert a byte into a two-digit hex number.
17

Another answer with later print/format style is:

res[0]=12
res[1]=23
print("my num is 0x{0:02x}{1:02x}".format(res[0],res[1]))

Comments

12

Convert the string to an integer base 16 then to hexadecimal.

print hex(int(string, base=16))

These are built-in functions.

http://docs.python.org/2/library/functions.html#int

Example

>>> string = 'AA'
>>> _int = int(string, base=16)
>>> _hex = hex(_int)
>>> print _int
170
>>> print _hex
0xaa
>>> 

Comments

2

You can try something like this I guess:

new_str = ""
str_value = "rojbasr"
for i in str_value:
    new_str += "0x%s " % (i.encode('hex'))
print new_str

Your output would be something like this:

0x72 0x6f 0x6a 0x62 0x61 0x73 0x72

2 Comments

I though he wanted to translate a string into hex and not to divide it into pairs of 2 . Its my fault that i didn't saw the example output
Not your fault, if you look at the history you'll see that the original question read that way. The OP couldn't decide what to name his/her variables, but I think I fixed it for him/her...
2

A way that will fail if your input string isn't valid pairs of hex characters...:

>>> import binascii
>>> ' '.join(hex(ord(i)) for i in binascii.unhexlify('deadbeef'))
'0xde 0xad 0xbe 0xef'

Comments

2

Use

print " ".join("0x%s"%my_string[i:i+2] for i in range(0, len(my_string), 2))

like this:

>>> my_string = "deadbeef"
>>> print " ".join("0x%s"%my_string[i:i+2] for i in range(0, len(my_string), 2))
0xde 0xad 0xbe 0xef
>>>

On an unrelated side note ... using string as a variable name even as an example variable name is very bad practice.

4 Comments

This looks like splitting a string into pairs of characters. I don't need that.
+1 for calling out using string as a variable name. Overwriting base types with variables can lead to incredibly frustrating debugging, trust me.
@Valdogg21: string isn't a base type-- that's str. It is the name of a stdlib module, however.
@DSM Woops. Major duh moment.
0

to display your payload only you can write this :

    def generate_payload():
    payload = b"\x16\x85\x04\x08"
    print(len(payload))
    return payload

if __name__ == "__main__":
    payload = generate_payload()
    print("Payload (représentation des caractères):")
    print(payload)
    
    # Afficher le payload en hexadécimal
    print("\nPayload (hexadécimal):")
    print(' '.join(f'{ord(c):02x}' for c in payload))

the b characters is for considering that is base 2 even its written in hexadecimal

to display characters before payload/ characters with payload , there is :

    def generate_payload():
    payload = "A" *128 +"\x16\x85\x04\x08"
    print(len(payload))
    return payload

if __name__ == "__main__":
    payload = generate_payload()
    print("Payload (représentation des caractères):")
    print(repr(payload))
    
    # Afficher le payload en hexadécimal
    print("\nPayload (hexadécimal):")
    print(' '.join(f'{ord(c):02x}' for c in payload))

the function repr can display theses patterns of characters

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.