bitstring.html


001| '''Bit String - a list of 0/1 bits.
001| 
001| Classes:
001|     bitstring       -a bitstring class
001| 
001| '''

002| ####################################################################################################
003| from sys import argv
004| from random import random
005| ####################################################################################################
006| BasePath = r'C:\CJS\prj\Python\ws'
007| 
008| BitTest = lambda value: 1 if bool(value) else 0
009| 
010| typename = lambda obj: type(obj).__name__
011| 
012| 
013| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
014| class bitstring:
015|     '''A bitstring class.'''
016| 
017|     def __init__ (self, bits=[], length=None, fill=0, sep='.'):
018|         '''New bitstring instance.'''
019|         self.bits = [BitTest(b) for b in bits]
020|         self.fill = BitTest(fill)
021|         self.sep = sep
022| 
023|         # Length check if length provided...
024|         if length is not None:
025|             if not isinstance(length, int):
026|                 raise ValueError(f'Length must be an integer, not {typename(n)}')
027| 
028|             # If specified length is smaller than bits...
029|             if length < len(self.bits):
030|                 # Truncate bits...
031|                 self.bits = self.bits[0:length]
032| 
033|             # If specified length is greater than bits...
034|             elif len(self.bits) < length:
035|                 self.bits[0:0] = [self.fill]*(length - len(self.bits))
036| 
037|     def force (self, value=0):
038|         bit = BitTest(value)
039|         self.bits = [bit for b in self.bits]
040|         return self
041| 
042|     def rotate_left (self, n):
043|         '''Rotate self data N bits to left..'''
044|         bitstring._positive_integer_check(n, 'Shift value')
045|         self.bits = self.bits[n:] + self.bits[:n]
046|         return self
047| 
048|     def rotate_right (self, n):
049|         '''Rotate self data N bits to right.'''
050|         bitstring._positive_integer_check(n, 'Shift value')
051|         self.bits = self.bits[-n:] + self.bits[:-n]
052|         return self
053| 
054|     def __call__ (self, function):
055|         '''Apply function to each bit. Function must take and return a bit.'''
056|         self.bits = [BitTest(function(b)) for b in self.bits]
057| 
058|     def __str__ (self):
059|         '''Return string comprised of bits.'''
060|         return self.sep.join(str(b) for b in self.bits)
061| 
062|     def __repr__ (self):
063|         return f'<{typename(self)} {len(self)} @{id(self):08x}>'
064| 
065|     # ============ List Operators ============
066|     def __len__ (self):
067|         '''Called for len(obj). Return length of bitstring.'''
068|         return len(self.bits)
069| 
070|     def __iter__ (self):
071|         '''Called for iter(obj). Return an iterator over bitstring.'''
072|         return iter(self.bits)
073| 
074|     def __getitem__ (self, ix):
075|         '''Called for obj[index]. Return an indexed bit from bitstring.
075|            NOTE: These functions get ranges like obj[3:-3:2]!'''

076|         return self.bits[ix]
077| 
078|     def __setitem__ (self, ix, val):
079|         '''Called for obj[index] = value. Set an indexed bit in bitstring.'''
080|         self.bits[ix] = BitTest(val)
081| 
082|     def __delitem__ (self, ix):
083|         '''Called for del obj[index].'''
084|         del self.bits[ix]
085| 
086|     def __contains__ (self, item):
087|         '''Called for {item in obj}. Return a boolean.'''
088|         return (item in self.bits)
089| 
090|     # ============ Object Views ============
091|     def __bool__ (self):
092|         '''Called for if obj. Return a boolean.'''
093|         return (0 < sum(self))
094| 
095|     def __int__ (self):
096|         '''Called for int(obj). Return an integer.'''
097|         val = 0
098|         factor = 1
099|         for b in self.bits:
100|             if b:
101|                 val += factor
102|             factor *= 2
103|         return val
104| 
105|     def __bytes__ (self):
106|         '''Called for bytes(obj). Return a bytes version.'''
107|         val = int(self)
108|         blen,rem = divmod(val.bit_length(), 8)
109|         blen += 1 if rem else 0
110|         return val.to_bytes(blen)
111| 
112|     def __reversed__ (self):
113|         '''Called for reversed(obj). Return reversed copy of bitstring.
113|            NOTE: Not called for obj[::-1]! That uses __getitem__.'''

114|         return reversed(self.bits)
115| 
116|     # ============ Relational Operators ============
117|     def __eq__ (self, other):
118|         '''Called for obj1==obj2. Return a boolean.'''
119|         bitstring._other_type_check(other)
120|         return self.bits == other.bits
121| 
122|     def __ne__ (self, other):
123|         '''Called for obj1!=obj2. Return a boolean.'''
124|         bitstring._other_type_check(other)
125|         return self.bits != other.bits
126| 
127|     def __lt__ (self, other):
128|         '''Called for obj1<obj2. Return a boolean.'''
129|         bitstring._other_type_check(other)
130|         return self.bits < other.bits
131| 
132|     def __le__ (self, other):
133|         '''Called for obj1<=obj2. Return a boolean.'''
134|         bitstring._other_type_check(other)
135|         return self.bits <= other.bits
136| 
137|     def __ge__ (self, other):
138|         '''Called for obj1>=obj2. Return a boolean.'''
139|         bitstring._other_type_check(other)
140|         return self.bits >= other.bits
141| 
142|     def __gt__ (self, other):
143|         '''Called for obj1>obj2. Return a boolean.'''
144|         bitstring._other_type_check(other)
145|         return self.bits > other.bits
146| 
147|     #NOTE: Done automagically because we define __eq__
148|     __hash__ = None
149| 
150|     # ============ Concatenate (+) and Multiply ============
151|     def _add_ (self, other):
152|         '''Add (concatenate) two bitstring.'''
153|         bitstring._other_type_check(other)
154|         return bitstring(self.bits + other.bits)
155| 
156|     def _mul_ (self, n):
157|         '''Multiply by integer for bitstring with N copies.'''
158|         bitstring._positive_integer_check(n, 'Multiplier')
159|         return bitstring(self.bits * n)
160| 
161|     def __add__ (self, other): return self._add_(other)
162|     def __radd__ (self, other): return self._add_(other)
163| 
164|     def __mul__ (self, n): return self._mul_(n)
165|     def __rmul__ (self, n): return self._mul_(n)
166| 
167|     # ============ Shift Operators ============
168|     def _left_shift_ (self, n):
169|         '''Shift data N bits to left..'''
170|         bitstring._positive_integer_check(n, 'Shift value')
171|         #TODO: check n <= len(self)
172|         return bitstring(self.bits[n:] + ([self.fill]*n))
173| 
174|     def _right_shift_ (self, n):
175|         '''Shift data N bits to right.'''
176|         bitstring._positive_integer_check(n, 'Shift value')
177|         #TODO: check n <= len(self)
178|         return bitstring(([self.fill]*n) + self.bits[:-n])
179| 
180|     def __lshift__ (self, n): return self._left_shift_(n)
181|     def __rlshift__ (self, n): return self._left_shift_(n)
182| 
183|     def __rshift__ (self, n): return self._right_shift_(n)
184|     def __rrshift__ (self, n): return self._right_shift_(n)
185| 
186|     # ============ Bit Operators (AND, OR, XOR) ============
187|     def _and_ (self, other):
188|         '''AND self and another bitstring.'''
189|         bitstring._other_type_check(other)
190|         res = [(a & b) for a,b in zip(self.bits,other.bits)]
191|         return bitstring(res)
192| 
193|     def _or_ (self, other):
194|         '''OR self and another bitstring.'''
195|         bitstring._other_type_check(other)
196|         res = [(a | b) for a,b in zip(self.bits,other.bits)]
197|         return bitstring(res)
198| 
199|     def _xor_ (self, other):
200|         '''XOR self and another bitstring.'''
201|         bitstring._other_type_check(other)
202|         res = [(a ^ b) for a,b in zip(self.bits,other.bits)]
203|         return bitstring(res)
204| 
205|     def __and__ (self, other): return self._and_(other)
206|     def __rand__ (self, other): return self._and_(other)
207| 
208|     def __or__ (self, other): return self._or_(other)
209|     def __ord__ (self, other): return self._or_(other)
210| 
211|     def __xor__ (self, other): return self._xor_(other)
212|     def __rxor__ (self, other): return self._xor_(other)
213| 
214|     # ============ In-place Operators ============
215|     def _iadd_ (self, other):
216|         '''Add (concatenate) bitstring to self.'''
217|         bitstring._other_type_check(other)
218|         return self.bits.extend(other.bits)
219| 
220|     def __imul__ (self, n):
221|         '''Multiply self.bits by integer N.'''
222|         bitstring._positive_integer_check(n, 'Multiplier')
223|         self.bits = self.bits * n
224|         return self
225| 
226|     def __ilshift__ (self, n):
227|         '''Shift self data N bits to left..'''
228|         bitstring._positive_integer_check(n, 'Shift value')
229|         #TODO: check n <= len(self)
230|         self.bits = self.bits[n:] + ([self.fill]*n)
231|         return self
232| 
233|     def __irshift__ (self, n):
234|         '''Shift self data N bits to right.'''
235|         bitstring._positive_integer_check(n, 'Shift value')
236|         #TODO: check n <= len(self)
237|         self.bits = ([self.fill]*n) + self.bits[:-n]
238|         return self
239| 
240|     def __iand__ (self, other):
241|         '''AND another bitstring with self.'''
242|         result = self._and_(other)
243|         self.bits = result.bits
244|         return self
245| 
246|     def __ior__ (self, other):
247|         '''AND another bitstring with self.'''
248|         result = self._or_(other)
249|         self.bits = result.bits
250|         return self
251| 
252|     def __ixor__ (self, other):
253|         '''AND another bitstring with self.'''
254|         result = self._xor_(other)
255|         self.bits = result.bits
256|         return self
257| 
258|     # ============ Utility Methods ============
259|     @classmethod
260|     def _other_type_check (cls, other):
261|         '''Ensure that other is the same type.'''
262|         if not isinstance(other, cls):
263|             raise TypeError(f'Expected a {cls.__name__} not a {typename(other)}')
264| 
265|     @staticmethod
266|     def _positive_integer_check (n, label):
267|         '''Ensure that N is a positive integer.'''
268|         if not isinstance(n, int):
269|             raise ValueError(f'{label} must be an integer, not {typename(n)}')
270|         if n < 0:
271|             raise ValueError(f'{label} must be a positive integer, not {n}')
272| 
273|     @staticmethod
274|     def from_integer (n, length=None, reverse=False):
275|         '''Return bitstring from integer bits.'''
276|         #ATTN: Not quite right?
277|         if not isinstance(n, int):
278|             raise ValueError(f'Input must be an integer, not {typename(n)}')
279| 
280|         # Generate bit string from integer...
281|         buf = []
282|         while n:
283|             n,b = divmod(n, 2)
284|             if reverse:
285|                 buf.insert(0, b)
286|             else:
287|                 buf.append(b)
288| 
289|         print(buf)
290|         # Return new bitstring object...
291|         return bitstring(buf, length=length)
292| 
293|     @staticmethod
294|     def from_string (s, length=None):
295|         '''Return bitstring from string of "0" and "1" characters.'''
296|         if not isinstance(s, str):
297|             raise ValueError(f'Input must be a string, not {typename(n)}')
298| 
299|         buf = [1 if ch=='1' else 0 for ch in s if ch in ['0','1']]
300|         # Generate and return new bitstring object...
301|         return bitstring(buf, length=length)
302| 
303|     @staticmethod
304|     def rand (length):
305|         '''Return a random bitstring.'''
306|         bitstring._positive_integer_check(length, 'Length')
307|         return bitstring(1 if 0.5 <= random() else 0 for _ in range(length))
308| 
309| 
310| ##================================================================================================##
311| def main (*args):
312|     bs0 = bitstring(length=32, fill=0)
313|     bs1 = bitstring(length=32, fill=1)
314|     bs2 = bitstring([0,0,1,1,1,1,0,0, 0,1,1,0,1,1,1,0,1,0,0,0,1,0,1,1, 0,0,0,0,1,1,1,1])
315|     bs3 = bitstring(ord(c) & 1 for c in 'Hello, World!')
316|     bs4 = bs0 + bs1
317|     bs5 = bs2 * 3
318|     bs6 = bitstring.from_integer(42, length=16, reverse=False)
319|     bs7 = bitstring.from_integer(42, length=16, reverse=True)
320|     bs8 = bitstring.from_string('11001010110011010')
321|     bs9 = bitstring.rand(32)
322|     rv = (bs0, bs1, bs2, bs3, bs4, bs5, bs6, bs7, bs8, bs9)
323| 
324|     for bs in rv:
325|         print(bs)
326|     print()
327|     return rv
328| 
329| ####################################################################################################
330| if __name__ == '__main__':
331|     print(argv[0])
332|     print()
333|     b0,b1,b2,b3,b4,b5,b6,b7,b8,b9 = main(*argv[1:])
334|     print()
335| ####################################################################################################
336| '''eof'''
337|