29.Strings and Number System

Python scripts can be written very efficiently  for the conversion of numbers into various bases.For example consider the conversion of binary number into equivalent decimal. The input is a string of bits representing the binary number and the output is the integer that the string represents.

Eg:input:1010 output:10

The algorithm uses a loop that accumulates the sum of a set of integers. The exponent that corresponds to the position of the string's  leftmost bit is the length of bit string minus 1.The loop visit the bits in the input string from left to right and counts the largest exponent of 2 down to 0 as it goes.Each bit is converted to its integer value, multiplied by its positional value and the result is added to the ongoing total.

bitstring=input("Enter a binary number...")
decno=0
expnt=len(bitstring)-1
for bit in bitstring:
    decno=decno+int(bit)* 2 ** expnt
    expnt=expnt-1
print ("The decimal number is=", decno)

We can also write Python script for converting decimal number into Binary.This algorithm repeatedly divides the decimal number by 2.After each division, the remainder( either 0 or 1) is placed at the beginning of a string of  bits.The quotient becomes the next dividend in the process.The binary string is initially is empty, and the process continues while the decimal number is greater than 0.

decno=int(input("Enter the decimal number...."))
if decno==0:
    print("The binary equivalent is....0000")
else:
    binaryno=""
    while decno!=0:
        b=decno%2
        binaryno=str(b)+binaryno
        decno=decno//2
    print("The binary equivalent is....",binaryno)

Note:Similar scripts can be used for converting decimal number to octal and hexa decimal and also their conversion back to decimal.

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020

46.Classes and Objects in Python- Accessors and mutators