开发者

How do I convert a base 10 float to hex in Python 2.4?

开发者 https://www.devze.com 2022-12-31 07:22 出处:网络
I trying开发者_JAVA百科 to convert numbers from decimal to hex. How do I convert float values to hex or char in Python 2.4.3?

I trying开发者_JAVA百科 to convert numbers from decimal to hex. How do I convert float values to hex or char in Python 2.4.3?

I would then like to be able to print it as ("\xa5\x (new hex number here)"). How do I do that?


From python 2.6.5 docs in hex(x) definition:

To obtain a hexadecimal string representation for a float, use the float.hex() method.


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


You can't convert a float directly to hex. You need to convert to int first.

hex(int(value))

Note that int always rounds down, so you might want to do the rounding explicitly before converting to int:

hex(int(round(value)))
0

精彩评论

暂无评论...
验证码 换一张
取 消