python 如何从有符号整数中获取十六进制字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/228702/
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
How to get hex string from signed integer
提问by Ellery Newcomer
Say I have the classic 4-byte signed integer, and I want something like
假设我有经典的 4 字节有符号整数,我想要类似的东西
print hex(-1)
打印十六进制(-1)
to give me something like
给我一些东西
>> 0xffffffff
>> 0xffffffff
In reality, the above gives me -0x1. I'm dawdling about in some lower level language, and python commandline is quick n easy.
实际上,上面给了我-0x1。我正在用一些较低级别的语言混日子,而且 python 命令行很快很容易。
So.. is there a way to do it?
那么..有没有办法做到这一点?
回答by paxdiablo
This will do the trick:
这将解决问题:
>>> print hex (-1 & 0xffffffff)
0xffffffffL
or, in function form (and stripping off the trailing "L"):
或者,以函数形式(并去掉尾随的“L”):
>>> def hex2(n):
... return hex (n & 0xffffffff)[:-1]
...
>>> print hex2(-1)
0xffffffff
>>> print hex2(17)
0x11
or, a variant that always returns fixed size (there may well be a better way to do this):
或者,一个总是返回固定大小的变体(很可能有更好的方法来做到这一点):
>>> def hex3(n):
... return "0x%s"%("00000000%s"%(hex(n&0xffffffff)[2:-1]))[-8:]
...
>>> print hex3(-1)
0xffffffff
>>> print hex3(17)
0x00000011
Or, avoiding the hex() altogether, thanks to Ignacio and bobince:
或者,完全避免使用 hex(),感谢 Ignacio 和 bobince:
def hex2(n):
return "0x%x"%(n&0xffffffff)
def hex3(n):
return "0x%s"%("00000000%x"%(n&0xffffffff))[-8:]
回答by Ignacio Vazquez-Abrams
Try this function:
试试这个功能:
'%#4x' % (-1 & 0xffffffff)
回答by Sai Gautam
"0x{:04x}".format((int(my_num) & 0xFFFF), '04x') , where my_num is the required number
"0x{:04x}".format((int(my_num) & 0xFFFF), '04x') ,其中 my_num 是所需的数字