如何将二进制(字符串)转换为浮点值? [英] How to convert a binary (string) into a float value?

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

问题描述

我想将二进制数转换为浮点数.这是一种可能性的示例:

<预><代码>>>>浮动(-0b1110)

给我正确的输出:

-14.0

不幸的是,我正在使用二进制字符串,即,我需要类似float('-0b1110')的东西.
但是,这不起作用:

>>>浮动('-0b1110')回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中ValueError:float() 的无效文字:-0b1110

我尝试使用 binascii.a2b_qp(string[, header]) 它将带引号的可打印数据块转换回二进制并返回二进制数据.但最终,我得到了同样的错误:

>>>浮动(binascii.a2b_qp('-0b1110'))回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中ValueError:float() 的无效文字:-0b1110

我理解输出数字是整数的情况,但如果我想获得数字 12.546 怎么办?那么二进制字符串的函数调用会是什么样的?

解决方案

另一种选择

from ast import literal_evalfloat_str = "-0b101010101"结果 = 浮点数(literal_eval(float_str))

与内置的eval"不同,literal_eval 即使在用户输入上也可以安全运行,因为它只能解析 Python 文字 - 并且不会执行表达式,这意味着它也不会调用函数.

I want to convert a binary number into a float number. Here's an example of a possibility:

>>> float(-0b1110)

gives me the correct output:

-14.0

Unfortunately, I am working with binary strings, i.e., I need something like float('-0b1110').
However, this doesn't work:

>>> float('-0b1110')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): -0b1110

I tried to use binascii.a2b_qp(string[, header]) which converts a block of quoted-printable data back to binary and returns the binary data. But eventually, I get the same error:

>>> float(binascii.a2b_qp('-0b1110'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): -0b1110

I understand the cases where the output number is an integer but what if I want to obtain the number 12.546? What would the function call for the binary string look like then?

解决方案

Another option is to do

from ast import literal_eval

float_str = "-0b101010101"
result = float(literal_eval(float_str))

Unlike the built-in "eval", literal_eval is safe to be run even on user inputs, as it can only parse Python literals - and will not execute expressions, which means it will not call functions as well.

这篇关于如何将二进制(字符串)转换为浮点值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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