Python-Ref > Data structures > Bit operations > Reading and writing individual bits
 
 

<-^^->
Moduly
Knihovní funkce

Reading and writing individual bits

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: (bits4-1.py)
  1   from bit_conv import int2bin
  2   
  3   def write_to_bit( num, bitnum):
  4     return num | (1 << bitnum)
  5   
  6   print write_to_bit( 0, 0)
  7   print write_to_bit( 0, 1)
  8   print write_to_bit( 0, 3)
  9   
 10   x = 0
 11   for i in range( 0, 8, 2):
 12     x = write_to_bit( x, i)
 13   print x
 14   print int2bin( x, 8)
stdout:
1
2
8
85
01010101
Doba běhu: 20.3 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: (bits4-2.py)
  1   from bit_conv import int2bin
  2   
  3   def read_bit( num, bitnum):
  4     return (num >> bitnum & 1)
  5   
  6   print read_bit( 8, 0)
  7   
  8   for i in range( 8):
  9     print read_bit( 85, i)
 10   print int2bin( 85, 8)
stdout:
0
1
0
1
0
1
0
1
0
01010101
Doba běhu: 20.8 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: (bits4-3.py)
  1   from bit_conv import int2bin
  2   
  3   def count_bits( num):
  4     count = 0
  5     while num:
  6       count += num & 1
  7       num >>= 1
  8     return count
  9   
 10   print count_bits( 8)
 11   print count_bits( 16)
 12   print count_bits( 85)
 13   print count_bits( 255)
stdout:
1
1
4
8
Doba běhu: 21.2 ms