社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Community Filipe Moisés  »  全部回复
回复总数  1
9 年前
回复了 Community Filipe Moisés 创建的主题 » 从python浮点类型到IEEE 64位浮点数组再回到python 3的最佳方式是什么?[重复]

在浏览了很多类似的问题后,我写了一些东西,希望能达到我的目的。

f = 1.00
negative = False
if f < 0:
    f = f*-1
    negative = True

s = struct.pack('>f', f)
p = struct.unpack('>l', s)[0]
hex_data =  hex(p)

scale = 16
num_of_bits = 32
binrep = bin(int(hex_data, scale))[2:].zfill(num_of_bits)
if negative:
    binrep = '1' + binrep[1:]

binrep 这就是结果。 每个部分都将被解释。


f = 1.00
negative = False
if f < 0:
    f = f*-1
    negative = True

如果为负数,则将数字转换为正数,并将变量负数设置为false。这是因为正数和负数的二进制表示之间的区别就在第一位,这是比用负数来计算整个过程中出现的错误更简单的方法。


s = struct.pack('>f', f)                          #'?\x80\x00\x00'
p = struct.unpack('>l', s)[0]                     #1065353216
hex_data =  hex(p)                                #'0x3f800000'

s 是二进制的十六进制表示形式 f .然而,它不是我需要的那种漂亮的形式。这就是p的作用。它是十六进制s的int表示,然后再进行一次转换,得到一个漂亮的十六进制。


scale = 16
num_of_bits = 32
binrep = bin(int(hex_data, scale))[2:].zfill(num_of_bits)
if negative:
    binrep = '1' + binrep[1:]

scale 是十六进制的基数16。 num_of_bits 是32,因为float是32位的,所以稍后会使用它来用0填充额外的位置,以达到32。有密码吗 宾雷普 从…起 this question .如果数字是负数,只需更改第一位。


我知道这很难看,但我没有找到一个好方法,我很快就需要它。欢迎评论。