Tweaks on BitStrings in Python
Wednesday, May 19, 2010
BitString is the best way of representing and handling bit strings in Python (how unsurprising). But, the point is, if sufficient care is not taken to do some tweaks in the representation, poor Python might end up having indigestion.
When using bit strings in python Bits and BitStrings, always make sure they are multiples of 4, and use bitstring.uint to convert them into unsigned integers before doing any bitwise operations between bit strings.
b = BitString(hex='0x11111111111111111111111111111111')
c = BitString(hex='0x10101011111111111010101111111111)'
d = b.__or__(c) #this will take insane amount of time.
#instead
b_val = b.uint
c_val = c.uint
d_val = b_val | d_val
d = BitString(uint=d_val, length=len(c))
This will do the trick, in a faster way. One more point is to convert int or uint to BitString, length always needs to be specified.
The main point to be noted here: if the bit string size is not a multiple of four, you can not use .hex or .uint properties of bitstring for its interpretation. So pad them accordingly.
0 comments:
Post a Comment