How to convert an int to a hex string?

730,817

Solution 1

You are looking for the chr function.

You seem to be mixing decimal representations of integers and hex representations of integers, so it's not entirely clear what you need. Based on the description you gave, I think one of these snippets shows what you want.

>>> chr(0x65) == '\x65'
True


>>> hex(65)
'0x41'
>>> chr(65) == '\x41'
True

Note that this is quite different from a string containing an integer as hex. If that is what you want, use the hex builtin.

Solution 2

This will convert an integer to a 2 digit hex string with the 0x prefix:

strHex = "0x%0.2X" % integerVariable

Solution 3

What about hex()?

hex(255)  # 0xff

If you really want to have \ in front you can do:

print '\\' + hex(255)[1:]

Solution 4

Let me add this one, because sometimes you just want the single digit representation

( x can be lower, 'x', or uppercase, 'X', the choice determines if the output letters are upper or lower.):

'{:x}'.format(15)
> f

And now with the new f'' format strings you can do:

f'{15:x}'
> f

To add 0 padding you can use 0>n:

f'{2034:0>4X}'
> 07F2

NOTE: the initial 'f' in f'{15:x}' is to signify a format string

Solution 5

Try:

"0x%x" % 255 # => 0xff

or

"0x%X" % 255 # => 0xFF

Python Documentation says: "keep this under Your pillow: http://docs.python.org/library/index.html"

Share:
730,817

Related videos on Youtube

pynoob
Author by

pynoob

Updated on May 12, 2022

Comments

  • pynoob
    pynoob almost 2 years

    I want to take an integer (that will be <= 255), to a hex string representation

    e.g.: I want to pass in 65 and get out '\x41', or 255 and get '\xff'.

    I've tried doing this with the struct.pack('c',65), but that chokes on anything above 9 since it wants to take in a single character string.

  • pacha
    pacha almost 12 years
    I suppose you mean "#%6x" % random.randint(0x0, 0xFFFFFF). (There is a missing % before 6 and randint takes 2 parameters -lower and upper bounds-)
  • diedthreetimes
    diedthreetimes over 11 years
    I thought chr converted integers to ascii. In which case chr(65) = 'A'. Is this a new addition?
  • Mike Graham
    Mike Graham over 11 years
    @diedthreetimes, chr does not involve ASCII at all--it simply takes a number and makes a one-byte bytestring where the ordinal value of the byte is the number. ASCII and ASCII-compatible encodings come into play when you write and display bytestrings.
  • Mike Graham
    Mike Graham over 11 years
    @diedthreetimes, For example, they come in by making 'A' another way to write and display '\x41'. All str really cares about is the fact this is sixty-five. To make things understandable and usable by humans, it often becomes an A.
  • Janus Troelsen
    Janus Troelsen over 11 years
    should be %06x if you don't want spaces
  • Glenn 'devalias' Grant
    Glenn 'devalias' Grant almost 8 years
    repr(chr(255)) # '\xff' also achieves this
  • Samuel
    Samuel about 7 years
    I suggest to edit the code here and change it to this: strHex = "0x%0.2X" % integerVariable. (I wasn't able to edit myself.)
  • Sean D.
    Sean D. about 6 years
    The amount of time it has taken me to find struct.pack('B', <integer>) is staggering. Thank you.
  • MFT
    MFT over 5 years
    For reference on this neat feature, PEP 498 -- Literal String Interpolation
  • Pavel Sapehin
    Pavel Sapehin about 4 years
    IMHO, a bit more "readable" option can be '0x{:X}'.format(15) (notice X is in uppercase). For 2034 it will print 0x7F2 instead of 7f2
  • James Stevens
    James Stevens almost 4 years
    hex(int(n,x))[2:] - not sure which is faster :)
  • grep
    grep about 3 years
    "%#x" % 255 :)
  • JPT
    JPT about 3 years
    Well... no. I tried hex(hash(text)) and it produced a negative integer which resulted in a hex string with minus sign. Who did implement this?
  • Luc
    Luc about 3 years
    @JPT I don't understand your question. If the value is negative, then obviously the hex value will have a minus sign. Why would that be different when writing in hexadecimal, binary, decimal, or any other number system? Or are you looking for the in-memory representation, where there is a bit that determines the sign by being set or unset?
  • JPT
    JPT about 3 years
    Well, the computer scientist is expecting negative hex to be something starting with a sign flag, so for example FFFx xxxx or 8000 xxxx, not an actual sign. I've never ever seen a hex with a minus sign before. But if you put it like that... ;)
  • Martin Thoma
    Martin Thoma about 2 years
    This should be more upvoted. f-strings for the win :-)