How to locate the bit in bits string?

Tim Chase python.list at tim.thechases.com
Tue Apr 28 14:44:13 EDT 2009


> I want to concatenate two bits string together: say we have '1001' and
> '111' which are represented in integer. I want to concatenate them to
> '1001111' (also in integer form), my method is:
> ('1001' << 3) | 111
> which is very time consuming.

You omit some key details -- namely how do you know that "1001" 
is 4 bits and not "00001001" (8-bits)?  If it's a string (as your 
current code shows), you can determine the length.  However, if 
they are actually ints, your code should work fine & be O(1).

This can be abstracted if you need:

   def combine_bits(int_a, int_b, bit_len_b):
     return (int_a << bit_len_b) | int_b

   a = 0x09
   b = 0x07
   print combine_bits(a, b, 3)

However, if you're using gargantuan ints (as discussed before), 
it's a lot messier.  You'd have to clarify the storage structure 
(a byte string?  a python long?)

-tkc

PS:  You may want to CC the mailing list so that others get a 
crack at answering your questions...I've been adding it back in, 
but you've been replying just to me.






More information about the Python-list mailing list