Page 35 - Programming With Python 3
P. 35

An Introduction to STEM Programming with Python — 2019-09-03a                               Page 22
            Chapter 2 — Numbering Systems



            And in Python we can do it, like:
             Free

               1|  n = 364
               2|  while(n):
               3|    r = n % 2
               4|    n = n //2
               5|    print(n,r)
             eBook

                    182 0
                    91 0
                    45 1
                    22 1
                    11 0
             Edition
                    5 1
                    2 1
                    1 0
                    0 1



            Binary to Decimal (Positional Method)
            Please support this work at

            To convert a binary number back to a decimal number we need to know our powers of 2 and just add
            them together.        http://syw2l.org

            If the binary number 101101101 actually represents
                                              4
                                                     3
                                       5
                         7
                                6
                                                           2
                  8
                                                                  1
                                                                               Free
              1×2 +0×2 +1×2 +1×2 +0×2 +1×2 +1×2 +0×2 +1×2                0  , then we should be able to add up the
            powers of two that are multiplied by 1 and ignore the powers multiplied by zero. So,
                                8
                                              5
                                                    3
                                                           2
                                       6
                                                                  0
              101101101 =1×2 +1×2 +1×2 +1×2 +1×2 +1×2 =256+64+32+8+4+1=365                     10  .
                         2
            Examples:
            Convert 100101011 2 to decimal:
                1 0 0   1 0 1 0 1 1                                eBook
             256       32    8    2 1
                                                                Edition
            299 10
            In Python we could write

               1|  print(2**8 + 2**5 + 2**3 + 2 + 1)


            Copyright 2019 — James M. Reneau Ph.D. — http://www.syw2l.org — This work is licensed
            under a Creative Commons Attribution-ShareAlike 4.0 International License.
   30   31   32   33   34   35   36   37   38   39   40