我试图将数字从十进制转换为十六进制。如何float
在 Python 2.4.3 中将值转换为十六进制或字符?
然后我希望能够将其打印为 ("\xa5\x (new hex number here)")。我怎么做?
我试图将数字从十进制转换为十六进制。如何float
在 Python 2.4.3 中将值转换为十六进制或字符?
然后我希望能够将其打印为 ("\xa5\x (new hex number here)")。我怎么做?
Judging from this comment:
would you mind please to give an example of its use? I am trying to convert this 0.554 to hex by using float.hex(value)? and how can I write it as (\x30\x30\x35\x35)? – jordan2010 1 hour ago
what you really want is a hexadecimal representation of the ASCII codes of those numerical characters rather than an actual float represented in hex.
"5" = 53(base 10) = 0x35 (base 16)
You can use ord() to get the ASCII code for each character like this:
>>> [ ord(char) for char in "0.554" ]
[48, 46, 53, 53, 52]
Do you want a human-readable representation? hex() will give you one but it is not in the same format that you asked for:
>>> [ hex(ord(char)) for char in "0.554" ]
['0x30', '0x2e', '0x35', '0x35', '0x34']
# 0 . 5 5 4
Instead you can use string substitution and appropriate formatters
res = "".join( [ "\\x%02X" % ord(char) for char in "0.554" ] )
>>> print res
\x30\x2E\x35\x35\x34
But if you want to serialize the data, look into using the struct
module to pack the data into buffers.
edited to answer jordan2010's second comment
Here's a quick addition to pad the number with leading zeroes.
>>> padded_integer_str = "%04d" % 5
>>> print padded_integer_str
0005
>>> res = "".join( [ "\\x%02X" % ord(char) for char in padded_integer_str] )
>>> print res
\x30\x30\x30\x35
See http://docs.python.org/library/stdtypes.html#string-formatting for an explanation on string formatters
来自hex(x) 定义中的python 2.6.5文档:
要获取浮点数的十六进制字符串表示,请使用 float.hex() 方法。
您不能将浮点数直接转换为十六进制。您需要先转换为 int。
hex(int(value))
请注意,int 总是向下舍入,因此您可能希望在转换为 int 之前明确地进行舍入:
hex(int(round(value)))