Package netaddr :: Module util
[hide private]
[frames] | no frames]

Source Code for Module netaddr.util

 1  #!/usr/bin/env python
 
 2  #-----------------------------------------------------------------------------
 
 3  #   Copyright (c) 2008-2009, David P. D. Moss. All rights reserved.
 
 4  #
 
 5  #   Released under the BSD license. See the LICENSE file for details.
 
 6  #-----------------------------------------------------------------------------
 
 7  """utility functions""" 
 8  
 
9 -def num_bits(n):
10 """Minimum number of bits needed to represent a given unsigned integer.""" 11 n = abs(n) 12 numbits = 0 13 while n: 14 numbits += 1 15 n >>= 1 16 return numbits
17 18 #-----------------------------------------------------------------------------
19 -def bytes_to_bits():
20 """ 21 Generates a 256 element list of 8-bit binary digit strings. List index is 22 equivalent to the bit string value. 23 """ 24 lookup = [] 25 bits_per_byte = range(7, -1, -1) 26 for num in range(256): 27 bits = 8*[None] 28 for i in bits_per_byte: 29 bits[i] = '01'[num&1] 30 num >>= 1 31 lookup.append(''.join(bits)) 32 return lookup
33 34 BYTES_TO_BITS = bytes_to_bits() 35