蟒蛇2.5:如何将浮点数转换为十六进制? [英] python 2.5: how to convert float to hex?

查看:188
本文介绍了蟒蛇2.5:如何将浮点数转换为十六进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用python 2.4 / 2.5转换一个float( time.time())输出。



我发现了很多将hex转换为float的例子,但是我找不到任何可以执行python> =>的 float.hex() 2.6是不可以的。

解决方案

它需要Python 2.6中新增的sys.float_info中的信息。



如果你想做非易携的,也就是说为你的特定平台,你需要查看用于生成2.4 / 5 Python的C编译器的 float.h 文件,或者查看2.6或2.7实现返回的sys.float_info你的平台(并相信它适用于你的2.4 / 5 Python)。然后你需要查看Python源文件(Objects / floatobject.c)中的 float_hex 函数,并将其转换为Python并对其进行测试(针对2.6 / 7的Python,也许)。

这似乎很多工作,为什么?你的目标是什么?你想做什么不能用 repr(your_float)



编辑:需要一个唯一的标识符

注意time.time()不是很精确:

< ()
time.time()
返回时间,以时间为单位,以UTC表示的浮点数以秒为单位。请注意,即使时间总是作为浮点数返回,并不是所有的系统都能提供比1秒更好的精确时间,而这个函数通常返回非递减的值,如果系统时钟已经在两次调用之间设置了,那么它可以返回比先前调用更低的值$ b $
$ b $ p $允许高达十亿分之一秒的分辨率:

 >>> (int(time.time()* 1000000000))
'0x11ef11c41cf98b00L'
>>>

是否足够好?


I want to convert a float (the output of time.time()) in hex using python 2.4/2.5.

I found tons of examples that convert hex to float, but I cannot find anything that allows me to do what the float.hex() of python >= 2.6 does.

解决方案

It can't be done portably in Python before version 2.6; it needs the information in sys.float_info, which is new in Python 2.6.

If you want to do it non-portably, i.e. for your particular platform, you would need to look at the float.h file for the C compiler that was used to produce your 2.4/5 Python, or at the sys.float_info returned by a 2.6 or 2.7 implementation on your platform (and trust that it applies to your 2.4/5 Python). Then you would need to look at the float_hex function in the Python source (Objects/floatobject.c) and translate that to Python and test it (against a 2.6/7 Python, perhaps).

This seems like a lot of work, for what? What is your goal? What do you want to do that can't be achieved with repr(your_float)?

Edit: need for a unique identifier

Note that time.time() is not very precise:

""" time.time() Return the time as a floating point number expressed in seconds since the epoch, in UTC. Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls. """

Allowing for up to a billionth of a second resolution:

>>> hex(int(time.time() * 1000000000))
'0x11ef11c41cf98b00L'
>>>

Is that good enough?

这篇关于蟒蛇2.5:如何将浮点数转换为十六进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆