How to convert an int to a hex string?
Asked Answered
G

15

305

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.

Golanka answered 16/2, 2010 at 0:7 Comment(0)
O
286

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.

Outcome answered 16/2, 2010 at 0:10 Comment(3)
I thought chr converted integers to ascii. In which case chr(65) = 'A'. Is this a new addition?Antiknock
@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.Outcome
@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.Outcome
G
157

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

strHex = "0x%0.2X" % integerVariable
Grieco answered 16/2, 2010 at 0:17 Comment(1)
I suggest to edit the code here and change it to this: strHex = "0x%0.2X" % integerVariable. (I wasn't able to edit myself.)Drogin
I
93

What about hex()?

hex(255)  # 0xff

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

print '\\' + hex(255)[1:]
Introspect answered 16/2, 2010 at 0:12 Comment(1)
repr(chr(255)) # '\xff' also achieves thisPertinacity
C
84

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

Chiseler answered 20/9, 2017 at 0:33 Comment(2)
For reference on this neat feature, PEP 498 -- Literal String InterpolationSacksen
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 7f2Guaiacol
C
51

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"

Crist answered 16/2, 2010 at 0:11 Comment(1)
"%#x" % 255 :)Curriery
P
34

For Python >= 3.6, use f-string formatting:

>>> x = 114514
>>> f'{x:0x}'
'1bf52'
>>> f'{x:#x}'
'0x1bf52'
Prefrontal answered 5/4, 2022 at 4:57 Comment(1)
This should be more upvoted. f-strings for the win :-)Sayce
N
13

If you want to pack a struct with a value <255 (one byte unsigned, uint8_t) and end up with a string of one character, you're probably looking for the format B instead of c. C converts a character to a string (not too useful by itself) while B converts an integer.

struct.pack('B', 65)

(And yes, 65 is \x41, not \x65.)

The struct class will also conveniently handle endianness for communication or other uses.

Narcisanarcissism answered 19/9, 2011 at 12:11 Comment(1)
The amount of time it has taken me to find struct.pack('B', <integer>) is staggering. Thank you.Loaded
T
13

With format(), as per format-examples, we can do:

>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'
Telestich answered 5/9, 2018 at 1:28 Comment(0)
M
12

Note that for large values, hex() still works (some other answers don't):

x = hex(349593196107334030177678842158399357)
print(x)

Python 2: 0x4354467b746f6f5f736d616c6c3f7dL
Python 3: 0x4354467b746f6f5f736d616c6c3f7d

For a decrypted RSA message, one could do the following:

import binascii

hexadecimals = hex(349593196107334030177678842158399357)

print(binascii.unhexlify(hexadecimals[2:-1])) # python 2
print(binascii.unhexlify(hexadecimals[2:])) # python 3
Mcnutt answered 5/10, 2016 at 21:29 Comment(5)
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?Unattached
@Unattached 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?Mcnutt
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... ;)Unattached
@Unattached the hext values you usually see are just a hex representation of a binary value. It is a matter of coding (Two's complement) that it is used in computer science. In the past different way of representing negative binary numbers were also used but Two's complement has biggest advantages.Jin
@Jin exactly, that's why a HEX with minus sign is not an exact representation. It's an interpretation.Unattached
B
11
(int_variable).to_bytes(bytes_length, byteorder='big'|'little').hex()

For example:

>>> (434).to_bytes(4, byteorder='big').hex()
'000001b2'
>>> (434).to_bytes(4, byteorder='little').hex()
'b2010000'
Bibelot answered 30/1, 2019 at 6:53 Comment(0)
T
8

This worked best for me

"0x%02X" % 5  # => 0x05
"0x%02X" % 17 # => 0x11

Change the (2) if you want a number with a bigger width (2 is for 2 hex printned chars) so 3 will give you the following

"0x%03X" % 5  # => 0x005
"0x%03X" % 17 # => 0x011
Transmittance answered 10/6, 2017 at 19:14 Comment(0)
C
7

Also you can convert any number in any base to hex. Use this one line code here it's easy and simple to use:

hex(int(n,x)).replace("0x","")

You have a string n that is your number and x the base of that number. First, change it to integer and then to hex but hex has 0x at the first of it so with replace we remove it.

Cripple answered 6/12, 2019 at 18:39 Comment(1)
hex(int(n,x))[2:] - not sure which is faster :)Leal
A
4

I wanted a random integer converted into a six-digit hex string with a # at the beginning. To get this I used

"#%6x" % random.randint(0xFFFFFF)
Astigmatism answered 22/1, 2012 at 22:15 Comment(2)
I suppose you mean "#%6x" % random.randint(0x0, 0xFFFFFF). (There is a missing % before 6 and randint takes 2 parameters -lower and upper bounds-)Latoyia
should be %06x if you don't want spacesArmorer
S
1

Use f-strings, it's easy to parse and quite flexible:

print(f'{255:x}')         # => 'ff'   
print(f'{15:2x}')         # => ' f'    
print(f'{15:02x}')        # => '0f'    
print(f'\\x{15:02x}')     # => '\x0f'  
Strop answered 31/10, 2023 at 10:19 Comment(0)
P
-1

As an alternative representation you could use

[in] '%s' % hex(15)
[out]'0xf'
Paternoster answered 28/7, 2017 at 3:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.