Python-Ref > Data structures > Bit operations > Binary to decadic and back again
 
 

<-^^->
Moduly
Knihovní funkce

Binary to decadic and back again

How to convert between binary and decadic representations.
Expand/Shrink
Zdroj: (bits2-1.py)
  1   # binary to decimal
  2   print int( "1110011", 2)
stdout:
115
Doba běhu: 18.1 ms
Expand/Shrink
Zdroj: (bits2-2.py)
  1   # decimal to binary (slightly more complicated)
  2   x = 115
  3   
  4   # dry run to show the idea
  5   num = x
  6   while num:
  7     print num & 1
  8     num >>= 1
  9   
 10   # now some real work
 11   num = x
 12   binary = ""
 13   while num:
 14     binary = str(num & 1) + binary
 15     num >>= 1
 16   
 17   print binary
 18   print int( binary, 2)
 19     
stdout:
1
1
0
0
1
1
1
1110011
115
Doba běhu: 18.5 ms
Expand/Shrink
Zdroj: (bit_conv.py)
  1   def int2bin( num, length=0):
  2     if not num:
  3       return "0".rjust( length, "0")
  4     binary = ""
  5     while num:
  6       binary = str(num & 1) + binary
  7       num >>= 1
  8     return binary.rjust( length, "0")
  9   
 10   if __name__ == "__main__":
 11     print int2bin( 8)
 12     print int2bin( 51, 8)
 13     
stdout:
1000
00110011
Doba běhu: 18.5 ms