如何在Python中将代表二进制分数的字符串转换为数字 [英] How to convert a string representing a binary fraction to a number in Python

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

问题描述

让我们假设我们有一个表示二进制分数的字符串,例如:

Let us suppose that we have a string representing a binary fraction such as:

".1"

作为十进制数字,为0.5.在Python中,有没有一种标准的方法可以将此类字符串转换为数字类型(严格来说,二进制还是十进制并不重要).

As a decimal number this is 0.5. Is there a standard way in Python to go from such strings to a number type (whether it is binary or decimal is not strictly important).

对于整数,解决方案很简单:

For an integer, the solution is straightforward:

int("101", 2)
>>>5

int()使用一个可选的第二个参数来提供基数,但float()没有.

int() takes an optional second argument to provide the base, but float() does not.

我正在寻找功能上等效的东西(我认为):

I am looking for something functionally equivalent (I think) to this:

def frac_bin_str_to_float(num):
    """Assuming num to be a string representing
    the fractional part of a binary number with
    no integer part, return num as a float."""
    result = 0
    ex = 2.0
    for c in num:
        if c == '1':
            result += 1/ex 
        ex *= 2
    return result

认为可以满足我的要求,尽管我可能会错过一些边缘情况.

I think that does what I want, although I may well have missed some edge cases.

在Python中是否有内置的或标准的方法?

Is there a built-in or standard method of doing this in Python?

推荐答案

以下是表达相同算法的较短方法:

The following is a shorter way to express the same algorithm:

def parse_bin(s):
    return int(s[1:], 2) / 2.**(len(s) - 1)

它假定字符串以点开头.如果您想要更一般的内容,则以下内容将处理整数和小数部分:

It assumes that the string starts with the dot. If you want something more general, the following will handle both the integer and the fractional parts:

def parse_bin(s):
    t = s.split('.')
    return int(t[0], 2) + int(t[1], 2) / 2.**len(t[1])

例如:

In [56]: parse_bin('10.11')
Out[56]: 2.75

这篇关于如何在Python中将代表二进制分数的字符串转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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