This article mainly introduces the mutual conversion function between decimal and binary decimals implemented in Python. It analyzes the principle of mutual conversion between binary and decimal in detail and the related Python implementation skills in the form of specific examples. Friends who need it can refer to it
The example in this article describes the mutual conversion function between decimal decimal and binary decimal implemented in Python. Share it with everyone for your reference, the details are as follows:
Decimal decimal ⇒ Binary decimal
Multiply by 2 and round up
##Multiply the decimal number by 2 to get the integer part and decimal part,
The integer part is the corresponding binary number,
then multiply the decimal part by 2 (the new decimal part is obtained after the previous multiplication), and then the integer and decimal parts are obtained.
Repeat this until the decimal part is 0 or reaches the accuracy requirement.
The first time the result is the highest bit, the last time The lowest bit is
, such as: 0.25 in binary 0.25*2=0.5 The rounding is 0 0.5*2=
1.0 Rounding is 1
01 ( The first time you get it is the highest bit, the last time you get it is the lowest bit)
The binary number of 0.81250.8125*2=1.625 The rounding is 1 0.625*2=
1.25 Rounding is 1 0.25*2=
0.5 Rounding is 0 0.5*2 =
1 . ## (The first result is the highest digit, the last result is the lowest digit)
def dec2bin(x): x -= int(x) bins = [] while x: x *= 2 bins.append(1 if x>=1. else 0) x -= int(x) return bins print(dec2bin(.8125)) # [1, 1, 0, 1]
Binary decimal ⇒ Decimal decimal
def bin2dec(b): d = 0 for i, x in enumerate(b): d += 2**(-i-1)*x return d print(dec2bin(0.8125)) # [1, 1, 0, 1] print(bin2dec(dec2bin(0.8125))) # 0.8125
The above is the detailed content of How to convert decimal and binary decimals in Python. For more information, please follow other related articles on the PHP Chinese website!