如何将int转换为十六进制字符串?

问题:如何将int转换为十六进制字符串?

我想将一个整数(将为<= 255)用于十六进制字符串表示形式

例如:我想通过65并离开'\x41',或255获得'\xff'

我曾尝试使用struct.pack('c',65来执行此操作),但9由于它想采用单个字符串,因此上述内容均会阻塞。

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.


回答 0

您正在寻找chr功能。

您似乎正在混合使用整数的十进制表示形式和整数的十六进制表示形式,因此尚不清楚您需要什么。根据您的描述,我认为这些片段之一可以显示您想要的内容。

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


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

请注意,这与包含整数(十六进制)的字符串完全不同。如果那是您想要的,请使用hex内置的。

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.


回答 1

这会将整数转换为带有0x前缀的2位十六进制字符串:

strHex = "0x%0.2X" % 255

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

strHex = "0x%0.2X" % 255

回答 2

hex()

hex(255)  # 0xff

如果您真的想\在前台就可以:

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

What about hex()?

hex(255)  # 0xff

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

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

回答 3

尝试:

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

要么

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

Python文档说:“把它放在枕头底下:http : //docs.python.org/library/index.html

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


回答 4

让我添加这一点,因为有时您只想用一位数字表示:

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

现在,使用新的f''格式字符串,您可以执行以下操作:

f'{15:x}'
> f

注意:最初的’f’ f'{15:x}'是表示格式字符串

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


回答 5

如果要打包一个值小于255的结构(一个无符号字节,uint8_t)并以一个字符的字符串结尾,则可能要寻找格式B而不是c。C将字符转换为字符串(本身不太有用),而B将整数转换。

struct.pack('B', 65)

(是的,65是\ x41,而不是\ x65。)

struct类还将方便地处理通讯或其他用途的字节序。

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.


回答 6

请注意,对于较大的值,hex()仍然可以使用(某些其他答案无效):

x = hex(349593196107334030177678842158399357)
print(x)

Python 2:0x4354467b746f6f5f736d616c6c3f7dL
Python 3:0x4354467b746f6f5f736d616c6c3f7d

对于解密的RSA消息,可以执行以下操作:

import binascii

hexadecimals = hex(349593196107334030177678842158399357)

print(binascii.unhexlify(hexadecimals[2:-1])) # python 2
print(binascii.unhexlify(hexadecimals[2:])) # python 3

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

回答 7

这对我来说最好

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

如果您想要一个更大的宽度(2是2个十六进制打印字符),请更改(2),这样3将为您提供以下内容

"0x%03X" % 5  # => 0x005
"0x%03X" % 17 # => 0x011

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

回答 8

我希望将一个随机整数转换为以#开头的六位十六进制字符串。为了得到这个我用了

"#%6x" % random.randint(0xFFFFFF)

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)

回答 9

随着format(),按照格式的例子,我们可以这样做:

>>> # 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'

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'

回答 10

(int_variable).to_bytes(bytes_length, byteorder='big'|'little').hex()

例如:

>>> (434).to_bytes(4, byteorder='big').hex()
'000001b2'
>>> (434).to_bytes(4, byteorder='little').hex()
'b2010000'
(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'

回答 11

您也可以将任何基数的任何数字转换为十六进制。在这里使用这一行代码很容易使用:

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

您有一个字符串n,该字符串是您的数字以及x 该数字的基数。首先,将其更改为整数,然后更改为十六进制,但是十六进制首先更改为十六进制0x,因此replace我们将其删除。

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.


回答 12

作为替代表示,您可以使用

[in] '%s' % hex(15)
[out]'0xf'

As an alternative representation you could use

[in] '%s' % hex(15)
[out]'0xf'