Python整数到带填充的十六进制字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40123901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:11:29  来源:igfitidea点击:

Python integer to hex string with padding

pythonhex

提问by SoonSYJ

Consider an integer 2. I want to convert it into hex string '0x02'. By using python's built-in function hex(), I can get '0x2' which is not suitable for my code. Can anyone show me how to get what I want in a convenient way? Thank you.

考虑一个整数 2。我想把它转换成十六进制字符串 '0x02'。通过使用python的内置函数hex(),我可以获得不适合我的代码的'0x2'。谁能告诉我如何以方便的方式获得我想要的东西?谢谢你。

回答by Michael Kopp

integer = 2
hex_string = '0x{:02x}'.format(integer)

See pep 3101, especially Standard Format Specifiersfor more info.

有关更多信息,请参阅pep 3101,尤其是标准格式说明符

回答by Erik Aronesty

For integers that might be very large:

对于可能非常大的整数:

integer = 2
hex = integer.to_bytes(((integer.bit_length() + 7) // 8),"big").hex()

The "big" refers to "big endian"... resulting in a string that is aligned visually as a human would expect.

“大”指的是“大端”……导致字符串在视觉上与人类期望的一样对齐。

You can then stick "0x" on the front if you want.

如果需要,您可以在前面贴上“0x”。

hex = "0x" + hex

回答by cdlane

>>> integer = 2
>>> hex_string = format(integer, '#04x')  # add 2 to field width for 0x
>>> hex_string
'0x02'

See Format Specification Mini-Language

请参阅格式规范迷你语言