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
Python integer to hex string with padding
提问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
回答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
请参阅格式规范迷你语言