python成绩转换,如何在Python中将代表二进制分数的字符串转换为数字

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

".1"

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() 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.

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])

For example:

In [56]: parse_bin('10.11')

Out[56]: 2.75

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值