Decimal 2 Binary Conversion in Python

From dftwiki3
Revision as of 12:59, 15 February 2017 by Thiebaut (talk | contribs) (Created page with "--~~~~ ---- <br /> =Source= <br /> ::<source lang="python"> from __future__ import print_function x = int( input( "> " ) ) binary = "" while True: if x==0: break re...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut (talk) 12:59, 15 February 2017 (EST)



Source


from __future__ import print_function

x = int( input( "> " ) )

binary = ""

while True:
    if x==0: break
    remainder = x % 2
    quotient  = x // 2

    if remainder == 0:
        binary = "0" + binary
    else:
        binary = "1" + binary

    print( "%5d = %5d * 2 + %d    quotien=%5d remainder=%d binary=%s"
           % (x, quotient, remainder, quotient, remainder, binary ) )

    x = quotient


Output


Python 3.3.6 (default, Aug 28 2015, 01:40:14) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
> 1234
 1234 =   617 * 2 + 0    quotien=  617 remainder=0 binary=0
  617 =   308 * 2 + 1    quotien=  308 remainder=1 binary=10
  308 =   154 * 2 + 0    quotien=  154 remainder=0 binary=010
  154 =    77 * 2 + 0    quotien=   77 remainder=0 binary=0010
   77 =    38 * 2 + 1    quotien=   38 remainder=1 binary=10010
   38 =    19 * 2 + 0    quotien=   19 remainder=0 binary=010010
   19 =     9 * 2 + 1    quotien=    9 remainder=1 binary=1010010
    9 =     4 * 2 + 1    quotien=    4 remainder=1 binary=11010010
    4 =     2 * 2 + 0    quotien=    2 remainder=0 binary=011010010
    2 =     1 * 2 + 0    quotien=    1 remainder=0 binary=0011010010
    1 =     0 * 2 + 1    quotien=    0 remainder=1 binary=10011010010
>>>