Python-Ref > Data structures > Bit operations > Bitwise operations
 
 

<-^^->
Moduly
Knihovní funkce

Bitwise operations

Expand/Shrink
  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     
Zdroj: (bits3-1.py)
  1   from bit_conv import int2bin
  2   
  3   print 11 & 5
  4   print int2bin( 11, 8)
  5   print int2bin( 5, 8)
  6   print int2bin( 11&5, 8)
  7   print "----------"
  8   print 203 & 87
  9   print int2bin( 203, 8)
 10   print int2bin( 87, 8)
 11   print int2bin( 203&87, 8)
 12   print "----------"
 13   print 203 | 87
 14   print int2bin( 203, 8)
 15   print int2bin( 87, 8)
 16   print int2bin( 203|87, 8)
 17   print "----------"
 18   print 203 ^ 87
 19   print int2bin( 203, 8)
 20   print int2bin( 87, 8)
 21   print int2bin( 203^87, 8)
stdout:
1
00001011
00000101
00000001
----------
67
11001011
01010111
01000011
----------
223
11001011
01010111
11011111
----------
156
11001011
01010111
10011100
Doba běhu: 27.0 ms
Expand/Shrink
  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     
Zdroj: (bits3-2.py)
  1   from bit_conv import int2bin
  2   
  3   # bitwise negation is strange as it inverts the sign bit as well
  4   print 51
  5   print ~51
  6   print 51 ^ ~0
  7   print ~51 ^ ~0
  8   
  9   # xor with a "full bitfield" is probably what we want
 10   print int2bin( 51, 8)
 11   print int2bin( 51 ^ 255, 8)
 12   
 13   print int2bin( 51, 16)
 14   print int2bin( 51 ^ 65535, 16)
stdout:
51
-52
-52
51
00110011
11001100
0000000000110011
1111111111001100
Doba běhu: 32.2 ms