Python decimal decimal and binary decimal conversion implementation mode

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.