Home  >  Article  >  Backend Development  >  How to convert decimal and binary decimals in Python

How to convert decimal and binary decimals in Python

黄舟
黄舟Original
2017-10-12 11:12:259051browse

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

, that is, the binary system of 0.25 is 0.

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.8125

0.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


After the decimal point, from left to right, each digit represents

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn