This article mainly introduces the implementation of the Python decimal decimal and binary fractional conversion function, combined with specific examples of the binary and decimal conversion of the principle and Python related implementation skills, the need for friends can refer to the next
The example in this paper is about the conversion of decimal decimal and binary decimal between Python implementations. Share to everyone for your reference, as follows:
Decimal decimal number ⇒ binary decimal
Take 2 to take the whole
The integer part and fractional part of the decimal decimal number multiply by 2,
The integer part is the corresponding binary digit,
Then 2 times the fractional part (the new fractional part is obtained before multiplying), and the integer and fractional parts are obtained.
Repeat until the number of decimal parts is 0 or the accuracy requirement is reached.
The first to get the highest bit, the last to get the lowest bit
Such as:
Binary in 0.25
0.25*2=0. 5 Rounding is 0
0.5*2=1. 0 Rounding is 1
That is, 0.25 of the binary is 0. (the first to get the highest bit, the last to get the lowest bit)
Binary in 0.8125
0.8125*2=1. 625 Rounding is 1
0.625*2=1. 25 Rounding is 1
0.25*2=0. 5 Rounding is 0
0.5*2=1. 0 Rounding is 1
That is, 0.8125 of the binary is 0. 1101(the first to get the highest bit, the last to get the lowest bit)
def dec2bin (x): x-= Int (x) bins = [] While x: x *= 2 bins.append (1 if x>=1. else 0) x-= Int (x ) return Binsprint (Dec2bin (. 8125)) # [1, 1, 0, 1]
binary decimal ⇒ Decimal Decimal
After the decimal point, from left to right, each person represents
def bin2dec (b): d = 0 for I, X in enumerate (b): D + = 2** (-i-1) *x return Dprint (Dec2bin (0.8125)) # [1, 1, 0, 1]print (Bin2dec (Dec2bin (0.8125)) # 0.8125