Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

Tuesday, May 7, 2013

Binary fraction to Decimal


Problem: Convert the given binary fraction to decimal.

Example:


binary_to_decimal_fraction(".1")
0.5

binary_to_decimal_fraction("0.0001100110011001")
0.0999908447265625

binary_to_decimal_fraction("0.01")
0.25

binary_to_decimal_fraction("0.0101100110011001")
0.3499908447265625


Solution in Python:

from __future__ import division

def binary_to_decimal_fraction(binary_str):
    """
    Author: Mayur P Srivastava
    """

    if binary_str[0] == '.':
        start_pos = 1
    elif binary_str[0] == '0' and binary_str[1] == '.':
        start_pos = 2
    else:
        assert False

    div     = 1
    decimal = 0

    for pos in range(start_pos, len(binary_str)):
        c = int(binary_str[pos])
        div *= 2

        decimal += c / div

    return decimal


Concepts Learned: Single loop, number system.

No comments:

Post a Comment