3 This package defines classes that simplify bit-wise creation, manipulation and
4 interpretation of data.
8 Bits -- An immutable container for binary data.
9 BitArray -- A mutable container for binary data.
10 ConstBitStream -- An immutable container with streaming methods.
11 BitStream -- A mutable container with streaming methods.
15 + mutating methods / \ + streaming methods
17 BitArray ConstBitStream
25 pack -- Create a BitStream from a format string.
29 Error -- Module exception base class.
30 CreationError -- Error during creation.
31 InterpretError -- Inappropriate interpretation of binary data.
32 ByteAlignError -- Whole byte position or length needed.
33 ReadError -- Reading or peeking past the end of a bitstring.
35 https://github.com/scott-griffiths/bitstring
41 Copyright (c) 2006-2016 Scott Griffiths (dr.scottgriffiths@gmail.com)
43 Permission is hereby granted, free of charge, to any person obtaining a copy
44 of this software and associated documentation files (the "Software"), to deal
45 in the Software without restriction, including without limitation the rights
46 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
47 copies of the Software, and to permit persons to whom the Software is
48 furnished to do so, subject to the following conditions:
50 The above copyright notice and this permission notice shall be included in
51 all copies or substantial portions of the Software.
53 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
54 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
55 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
56 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
57 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
58 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
64 __author__ =
"Scott Griffiths"
78 byteorder = sys.byteorder
81 """Determines whether a number of methods default to working only on byte boundaries."""
91 """Base class for errors in the bitstring module."""
93 def __init__(self, *params):
94 self.
msg = params[0]
if params
else ''
104 """Reading or peeking past the end of a bitstring."""
106 def __init__(self, *params):
107 Error.__init__(self, *params)
111 """Inappropriate interpretation of binary data."""
113 def __init__(self, *params):
114 Error.__init__(self, *params)
118 """Whole-byte position or length needed."""
120 def __init__(self, *params):
121 Error.__init__(self, *params)
125 """Inappropriate argument during bitstring creation."""
127 def __init__(self, *params):
128 Error.__init__(self, *params)
132 """Stores raw bytes together with a bit offset and length.
134 Used internally - not part of public interface.
137 __slots__ = (
'offset',
'_rawarray',
'bitlength')
139 def __init__(self, data, bitlength=None, offset=None):
140 """data is either a bytearray or a MmapByteArray"""
144 if bitlength
is None:
145 bitlength = 8 * len(data) - offset
149 def getbit(self, pos):
151 byte, bit = divmod(self.
offset + pos, 8)
152 return bool(self.
_rawarray[byte] & (128 >> bit))
155 """Direct access to byte data."""
159 """Direct access to byte data."""
164 def bytelength(self):
175 """Join another store on to the end of this one."""
176 if not store.bitlength:
182 joinval = (self.
_rawarray.pop() & (255 ^ (255 >> store.offset)) |
183 (store.getbyte(0) & (255 >> store.offset)))
185 self.
_rawarray.extend(store._rawarray[1:])
191 """Join another store on to the start of this one."""
192 if not store.bitlength:
198 assert (store.offset + store.bitlength) % 8 == self.
offset % 8
199 bit_offset = self.
offset % 8
202 store.setbyte(-1, (store.getbyte(-1) & (255 ^ (255 >> bit_offset)) |
208 self.
offset = store.offset
212 def byteoffset(self):
221 """Adding mutating methods to ConstByteStore
223 Used internally - not part of public interface.
227 def setbit(self, pos):
229 byte, bit = divmod(self.
offset + pos, 8)
232 def unsetbit(self, pos):
234 byte, bit = divmod(self.
offset + pos, 8)
237 def invertbit(self, pos):
239 byte, bit = divmod(self.
offset + pos, 8)
242 def setbyte(self, pos, value):
245 def setbyteslice(self, start, end, value):
250 """Return a copy of a ByteStore with the newoffset.
252 Not part of public interface.
254 assert 0 <= newoffset < 8
258 if newoffset == s.offset % 8:
259 return ByteStore(s.getbyteslice(s.byteoffset, s.byteoffset + s.bytelength), s.bitlength, newoffset)
262 assert newoffset != s.offset % 8
263 if newoffset < s.offset % 8:
265 shiftleft = s.offset % 8 - newoffset
267 for x
in range(s.byteoffset, s.byteoffset + s.bytelength - 1):
268 newdata.append(((d[x] << shiftleft) & 0xff) +
269 (d[x + 1] >> (8 - shiftleft)))
270 bits_in_last_byte = (s.offset + s.bitlength) % 8
271 if not bits_in_last_byte:
272 bits_in_last_byte = 8
273 if bits_in_last_byte > shiftleft:
274 newdata.append((d[s.byteoffset + s.bytelength - 1] << shiftleft) & 0xff)
276 shiftright = newoffset - s.offset % 8
277 newdata.append(s.getbyte(0) >> shiftright)
278 for x
in range(s.byteoffset + 1, s.byteoffset + s.bytelength):
279 newdata.append(((d[x - 1] << (8 - shiftright)) & 0xff) +
280 (d[x] >> shiftright))
281 bits_in_last_byte = (s.offset + s.bitlength) % 8
282 if not bits_in_last_byte:
283 bits_in_last_byte = 8
284 if bits_in_last_byte + shiftright > 8:
285 newdata.append((d[s.byteoffset + s.bytelength - 1] << (8 - shiftright)) & 0xff)
286 new_s =
ByteStore(bytearray(newdata), s.bitlength, newoffset)
287 assert new_s.offset == newoffset
292 """Return True if ByteStores a == b.
294 Not part of public interface.
299 a_bitlength = a.bitlength
300 b_bitlength = b.bitlength
301 if a_bitlength != b_bitlength:
304 assert b_bitlength == 0
307 if (a.offset % 8) > (b.offset % 8):
310 a_bitoff = a.offset % 8
311 b_bitoff = b.offset % 8
312 a_byteoffset = a.byteoffset
313 b_byteoffset = b.byteoffset
314 a_bytelength = a.bytelength
315 b_bytelength = b.bytelength
320 if da
is db
and a.offset == b.offset:
323 if a_bitoff == b_bitoff:
324 bits_spare_in_last_byte = 8 - (a_bitoff + a_bitlength) % 8
325 if bits_spare_in_last_byte == 8:
326 bits_spare_in_last_byte = 0
328 if a_bytelength == 1:
329 a_val = ((da[a_byteoffset] << a_bitoff) & 0xff) >> (8 - a_bitlength)
330 b_val = ((db[b_byteoffset] << b_bitoff) & 0xff) >> (8 - b_bitlength)
331 return a_val == b_val
333 if da[a_byteoffset] & (0xff >> a_bitoff) != db[b_byteoffset] & (0xff >> b_bitoff):
336 b_a_offset = b_byteoffset - a_byteoffset
337 for x
in range(1 + a_byteoffset, a_byteoffset + a_bytelength - 1):
338 if da[x] != db[b_a_offset + x]:
341 return (da[a_byteoffset + a_bytelength - 1] >> bits_spare_in_last_byte ==
342 db[b_byteoffset + b_bytelength - 1] >> bits_spare_in_last_byte)
344 assert a_bitoff != b_bitoff
346 shift = b_bitoff - a_bitoff
348 if b_bytelength == 1:
349 assert a_bytelength == 1
350 a_val = ((da[a_byteoffset] << a_bitoff) & 0xff) >> (8 - a_bitlength)
351 b_val = ((db[b_byteoffset] << b_bitoff) & 0xff) >> (8 - b_bitlength)
352 return a_val == b_val
354 if a_bytelength == 1:
355 assert b_bytelength == 2
356 a_val = ((da[a_byteoffset] << a_bitoff) & 0xff) >> (8 - a_bitlength)
357 b_val = ((db[b_byteoffset] << 8) + db[b_byteoffset + 1]) << b_bitoff
359 b_val >>= 16 - b_bitlength
360 return a_val == b_val
363 if (da[a_byteoffset] & (0xff >> a_bitoff)) >> shift != db[b_byteoffset] & (0xff >> b_bitoff):
366 for x
in range(1, b_bytelength - 1):
368 b_val = db[b_byteoffset + x]
369 a_val = ((da[a_byteoffset + x - 1] << 8) + da[a_byteoffset + x]) >> shift
375 final_b_bits = (b.offset + b_bitlength) % 8
378 b_val = db[b_byteoffset + b_bytelength - 1] >> (8 - final_b_bits)
379 final_a_bits = (a.offset + a_bitlength) % 8
382 if b.bytelength > a_bytelength:
383 assert b_bytelength == a_bytelength + 1
384 a_val = da[a_byteoffset + a_bytelength - 1] >> (8 - final_a_bits)
385 a_val &= 0xff >> (8 - final_b_bits)
386 return a_val == b_val
387 assert a_bytelength == b_bytelength
388 a_val = da[a_byteoffset + a_bytelength - 2] << 8
389 a_val += da[a_byteoffset + a_bytelength - 1]
390 a_val >>= (8 - final_a_bits)
391 a_val &= 0xff >> (8 - final_b_bits)
392 return a_val == b_val
396 """Looks like a bytearray, but from an mmap.
398 Not part of public interface.
401 __slots__ = (
'filemap',
'filelength',
'source',
'byteoffset',
'bytelength')
403 def __init__(self, source, bytelength=None, byteoffset=None):
405 source.seek(0, os.SEEK_END)
407 if byteoffset
is None:
409 if bytelength
is None:
413 self.
filemap = mmap.mmap(source.fileno(), 0, access=mmap.ACCESS_READ)
415 def __getitem__(self, key):
419 except AttributeError:
431 assert key.step
is None
435 return bytearray(self.
filemap.__getitem__(s))
443 BYTE_REVERSAL_DICT = dict()
450 BYTE_REVERSAL_DICT[i] = chr(int(
"{0:08b}".format(i)[::-1], 2))
453 BYTE_REVERSAL_DICT[i] = bytes([int(
"{0:08b}".format(i)[::-1], 2)])
454 from io
import IOBase
as file
459 LEADING_OCT_CHARS = len(oct(1)) - 1
463 """Return string made lowercase and with all whitespace removed."""
464 s =
''.join(s.split()).lower()
468 INIT_NAMES = (
'uint',
'int',
'ue',
'se',
'sie',
'uie',
'hex',
'oct',
'bin',
'bits',
469 'uintbe',
'intbe',
'uintle',
'intle',
'uintne',
'intne',
470 'float',
'floatbe',
'floatle',
'floatne',
'bytes',
'bool',
'pad')
472 TOKEN_RE = re.compile(
r'(?P<name>' +
'|'.join(INIT_NAMES) +
473 r')((:(?P<len>[^=]+)))?(=(?P<value>.*))?$', re.IGNORECASE)
474 DEFAULT_UINT = re.compile(
r'(?P<len>[^=]+)?(=(?P<value>.*))?$', re.IGNORECASE)
476 MULTIPLICATIVE_RE = re.compile(
r'(?P<factor>.*)\*(?P<token>.+)')
479 LITERAL_RE = re.compile(
r'(?P<name>0(x|o|b))(?P<value>.+)', re.IGNORECASE)
482 STRUCT_PACK_RE = re.compile(
r'(?P<endian><|>|@)?(?P<fmt>(?:\d*[bBhHlLqQfd])+)$')
485 STRUCT_SPLIT_RE = re.compile(
r'\d*[bBhHlLqQfd]')
489 REPLACEMENTS_BE = {
'b':
'intbe:8',
'B':
'uintbe:8',
490 'h':
'intbe:16',
'H':
'uintbe:16',
491 'l':
'intbe:32',
'L':
'uintbe:32',
492 'q':
'intbe:64',
'Q':
'uintbe:64',
493 'f':
'floatbe:32',
'd':
'floatbe:64'}
495 REPLACEMENTS_LE = {
'b':
'intle:8',
'B':
'uintle:8',
496 'h':
'intle:16',
'H':
'uintle:16',
497 'l':
'intle:32',
'L':
'uintle:32',
498 'q':
'intle:64',
'Q':
'uintle:64',
499 'f':
'floatle:32',
'd':
'floatle:64'}
502 PACK_CODE_SIZE = {
'b': 1,
'B': 1,
'h': 2,
'H': 2,
'l': 4,
'L': 4,
503 'q': 8,
'Q': 8,
'f': 4,
'd': 8}
505 _tokenname_to_initialiser = {
'hex':
'hex',
'0x':
'hex',
'0X':
'hex',
'oct':
'oct',
506 '0o':
'oct',
'0O':
'oct',
'bin':
'bin',
'0b':
'bin',
507 '0B':
'bin',
'bits':
'auto',
'bytes':
'bytes',
'pad':
'pad'}
511 """Parse struct-like format string token into sub-token list."""
512 m = STRUCT_PACK_RE.match(token)
516 endian = m.group(
'endian')
520 formatlist = re.findall(STRUCT_SPLIT_RE, m.group(
'fmt'))
522 fmt =
''.join([f[-1] * int(f[:-1])
if len(f) != 1
else
523 f
for f
in formatlist])
526 if byteorder ==
'little':
529 assert byteorder ==
'big'
532 tokens = [REPLACEMENTS_LE[c]
for c
in fmt]
535 tokens = [REPLACEMENTS_BE[c]
for c
in fmt]
540 """Divide the format string into tokens and parse them.
542 Return stretchy token and list of [initialiser, length, value]
543 initialiser is one of: hex, oct, bin, uint, int, se, ue, 0x, 0o, 0b etc.
544 length is None if not known, as is value.
546 If the token is in the keyword dictionary (keys) then it counts as a
547 special case and isn't messed with.
549 tokens must be of the form: [factor*][initialiser][:][length][=value]
553 return token_cache[(fmt, keys)]
555 token_key = (fmt, keys)
561 meta_tokens = (
''.join(f.split())
for f
in fmt.split(
','))
563 stretchy_token =
False
564 for meta_token
in meta_tokens:
566 m = MULTIPLICATIVE_RE.match(meta_token)
570 factor = int(m.group(
'factor'))
571 meta_token = m.group(
'token')
576 if keys
and token
in keys:
578 ret_vals.append([token,
None,
None])
580 value = length =
None
584 m = LITERAL_RE.match(token)
586 name = m.group(
'name')
587 value = m.group(
'value')
588 ret_vals.append([name, length, value])
591 m1 = TOKEN_RE.match(token)
594 m2 = DEFAULT_UINT.match(token)
596 raise ValueError(
"Don't understand token '{0}'.".format(token))
598 name = m1.group(
'name')
599 length = m1.group(
'len')
600 if m1.group(
'value'):
601 value = m1.group(
'value')
605 length = m2.group(
'len')
606 if m2.group(
'value'):
607 value = m2.group(
'value')
609 if length
is not None:
610 raise ValueError(
"You can't specify a length with bool tokens - they are always one bit.")
612 if length
is None and name
not in (
'se',
'ue',
'sie',
'uie'):
613 stretchy_token =
True
614 if length
is not None:
624 raise ValueError(
"Can't read a token with a negative length.")
626 if not keys
or length
not in keys:
627 raise ValueError(
"Don't understand length '{0}' of token.".format(length))
628 ret_vals.append([name, length, value])
634 return_values.extend(ret_vals * factor)
635 return_values = [tuple(x)
for x
in return_values]
636 if len(token_cache) < CACHE_SIZE:
637 token_cache[token_key] = stretchy_token, return_values
638 return stretchy_token, return_values
642 BRACKET_RE = re.compile(
r'(?P<factor>\d+)\*\(')
646 """Remove whitespace and expand all brackets."""
647 s =
''.join(s.split())
663 raise ValueError(
"Unbalanced parenthesis in '{0}'.".format(s))
664 if start == 0
or s[start - 1] !=
'*':
665 s = s[0:start] + s[start + 1:p] + s[p + 1:]
667 m = BRACKET_RE.search(s)
669 factor = int(m.group(
'factor'))
670 matchstart = m.start(
'factor')
671 s = s[0:matchstart] + (factor - 1) * (s[start + 1:p] +
',') + s[start + 1:p] + s[p + 1:]
673 raise ValueError(
"Failed to parse '{0}'.".format(s))
678 OCT_TO_BITS = [
'{0:03b}'.format(i)
for i
in xrange(8)]
681 BIT_COUNT = dict(zip(xrange(256), [bin(i).count(
'1')
for i
in xrange(256)]))
685 """A container holding an immutable sequence of bits.
687 For a mutable container use the BitArray class instead.
691 all() -- Check if all specified bits are set to 1 or 0.
692 any() -- Check if any of specified bits are set to 1 or 0.
693 count() -- Count the number of bits set to 1 or 0.
694 cut() -- Create generator of constant sized chunks.
695 endswith() -- Return whether the bitstring ends with a sub-string.
696 find() -- Find a sub-bitstring in the current bitstring.
697 findall() -- Find all occurrences of a sub-bitstring in the current bitstring.
698 join() -- Join bitstrings together using current bitstring.
699 rfind() -- Seek backwards to find a sub-bitstring.
700 split() -- Create generator of chunks split by a delimiter.
701 startswith() -- Return whether the bitstring starts with a sub-bitstring.
702 tobytes() -- Return bitstring as bytes, padding if needed.
703 tofile() -- Write bitstring to file, padding if needed.
704 unpack() -- Interpret bits using format string.
708 Also available are the operators [], ==, !=, +, *, ~, <<, >>, &, |, ^.
712 bin -- The bitstring as a binary string.
713 bool -- For single bit bitstrings, interpret as True or False.
714 bytes -- The bitstring as a bytes object.
715 float -- Interpret as a floating point number.
716 floatbe -- Interpret as a big-endian floating point number.
717 floatle -- Interpret as a little-endian floating point number.
718 floatne -- Interpret as a native-endian floating point number.
719 hex -- The bitstring as a hexadecimal string.
720 int -- Interpret as a two's complement signed integer.
721 intbe -- Interpret as a big-endian signed integer.
722 intle -- Interpret as a little-endian signed integer.
723 intne -- Interpret as a native-endian signed integer.
724 len -- Length of the bitstring in bits.
725 oct -- The bitstring as an octal string.
726 se -- Interpret as a signed exponential-Golomb code.
727 ue -- Interpret as an unsigned exponential-Golomb code.
728 sie -- Interpret as a signed interleaved exponential-Golomb code.
729 uie -- Interpret as an unsigned interleaved exponential-Golomb code.
730 uint -- Interpret as a two's complement unsigned integer.
731 uintbe -- Interpret as a big-endian unsigned integer.
732 uintle -- Interpret as a little-endian unsigned integer.
733 uintne -- Interpret as a native-endian unsigned integer.
737 __slots__ = (
'_datastore')
739 def __init__(self, auto=None, length=None, offset=None, **kwargs):
740 """Either specify an 'auto' initialiser:
741 auto -- a string of comma separated tokens, an integer, a file object,
742 a bytearray, a boolean iterable, an array or another bitstring.
744 Or initialise via **kwargs with one (and only one) of:
745 bytes -- raw data as a string, for example read from a binary file.
746 bin -- binary string representation, e.g. '0b001010'.
747 hex -- hexadecimal string representation, e.g. '0x2ef'
748 oct -- octal string representation, e.g. '0o777'.
749 uint -- an unsigned integer.
750 int -- a signed integer.
751 float -- a floating point number.
752 uintbe -- an unsigned big-endian whole byte integer.
753 intbe -- a signed big-endian whole byte integer.
754 floatbe - a big-endian floating point number.
755 uintle -- an unsigned little-endian whole byte integer.
756 intle -- a signed little-endian whole byte integer.
757 floatle -- a little-endian floating point number.
758 uintne -- an unsigned native-endian whole byte integer.
759 intne -- a signed native-endian whole byte integer.
760 floatne -- a native-endian floating point number.
761 se -- a signed exponential-Golomb code.
762 ue -- an unsigned exponential-Golomb code.
763 sie -- a signed interleaved exponential-Golomb code.
764 uie -- an unsigned interleaved exponential-Golomb code.
765 bool -- a boolean (True or False).
766 filename -- a file which will be opened in binary read-only mode.
768 Other keyword arguments:
769 length -- length of the bitstring in bits, if needed and appropriate.
770 It must be supplied for all integer and float initialisers.
771 offset -- bit offset to the data. These offset bits are
772 ignored and this is mainly intended for use when
773 initialising using 'bytes' or 'filename'.
778 def __new__(cls, auto=None, length=None, offset=None, _cache={}, **kwargs):
782 if isinstance(auto, basestring):
786 x = object.__new__(Bits)
789 except ValueError
as e:
793 x._datastore._appendstore(Bits._init_with_token(*token)._datastore)
794 assert x._assertsanity()
795 if len(_cache) < CACHE_SIZE:
798 if isinstance(auto, Bits):
802 x = super(Bits, cls).__new__(cls)
803 x._initialise(auto, length, offset, **kwargs)
806 def _initialise(self, auto, length, offset, **kwargs):
807 if length
is not None and length < 0:
809 if offset
is not None and offset < 0:
812 self._initialise_from_auto(auto, length, offset)
816 if length
is not None and length != 0:
817 data = bytearray((length + 7) // 8)
818 self._setbytes_unsafe(data, length, 0)
820 self._setbytes_unsafe(bytearray(0), 0, 0)
822 k, v = kwargs.popitem()
824 init_without_length_or_offset[k](self, v)
825 if length
is not None or offset
is not None:
826 raise CreationError(
"Cannot use length or offset with this initialiser.")
829 init_with_length_only[k](self, v, length)
830 if offset
is not None:
831 raise CreationError(
"Cannot use offset with this initialiser.")
836 init_with_length_and_offset[k](self, v, length, offset)
838 raise CreationError(
"Unrecognised keyword '{0}' used to initialise.", k)
840 def _initialise_from_auto(self, auto, length, offset):
843 self._setauto(auto, length, offset)
847 """Return a new copy of the Bits for the copy module."""
852 def __lt__(self, other):
853 raise TypeError(
"unorderable type: {0}".format(type(self).__name__))
855 def __gt__(self, other):
856 raise TypeError(
"unorderable type: {0}".format(type(self).__name__))
858 def __le__(self, other):
859 raise TypeError(
"unorderable type: {0}".format(type(self).__name__))
861 def __ge__(self, other):
862 raise TypeError(
"unorderable type: {0}".format(type(self).__name__))
865 """Concatenate bitstrings and return new bitstring.
867 bs -- the bitstring to append.
871 if bs.len <= self.
len:
876 s = self.__class__(s)
881 """Append current bitstring to bs and return new bitstring.
883 bs -- the string for the 'auto' initialiser that will be appended to.
887 return bs.__add__(self)
890 """Return a new bitstring representing a slice of the current bitstring.
892 Indices are in units of the step parameter (default 1 bit).
893 Stepping is used to specify the number of bits in each item.
895 >>> print BitArray('0b00110')[1:4]
897 >>> print BitArray('0x00112233')[1:3:8]
903 step = key.step
if key.step
is not None else 1
904 except AttributeError:
908 if not 0 <= key < length:
909 raise IndexError(
"Slice index out of range.")
915 bs = self.__class__()
918 start, stop = 0, length
919 if key.start
is not None:
923 if key.stop
is not None:
927 start = max(start, 0)
928 stop = min(stop, length)
930 return self.
_slice(start, stop)
932 return self.__class__()
935 """Return the length of the bitstring in bits."""
939 """Return approximate string representation of bitstring for printing.
941 Short strings will be given wholly in hexadecimal or binary. Longer
942 strings may be part hexadecimal and part binary. Very long strings will
943 be truncated with '...'.
949 if length > MAX_CHARS * 4:
951 return ''.
join((
'0x', self.
_readhex(MAX_CHARS * 4, 0),
'...'))
953 if length < 32
and length % 4 != 0:
954 return '0b' + self.
bin
957 return '0x' + self.
hex
960 bits_at_end = length % 4
961 return ''.
join((
'0x', self.
_readhex(length - bits_at_end, 0),
963 self.
_readbin(bits_at_end, length - bits_at_end)))
966 """Return representation that could be used to recreate the bitstring.
968 If the returned string is too long it will be truncated. See __str__().
972 if isinstance(self.
_datastore._rawarray, MmapByteArray):
975 offsetstring =
", offset=%d" % (self.
_datastore._rawarray.byteoffset * 8 + self.
_offset)
976 lengthstring =
", length=%d" % length
977 return "{0}(filename='{1}'{2}{3})".format(self.__class__.__name__,
978 self.
_datastore._rawarray.source.name, lengthstring, offsetstring)
982 if s.endswith(
'...'):
983 lengthstring =
" # length={0}".format(length)
984 return "{0}('{1}'){2}".format(self.__class__.__name__, s, lengthstring)
987 """Return True if two bitstrings have the same binary representation.
989 >>> BitArray('0b1110') == '0xe'
1000 """Return False if two bitstrings have the same binary representation.
1002 >>> BitArray('0b111') == '0x7'
1006 return not self.
__eq__(bs)
1009 """Return bitstring with every bit inverted.
1011 Raises Error if the bitstring is empty.
1015 raise Error(
"Cannot invert empty bitstring.")
1021 """Return bitstring with bits shifted by n to the left.
1023 n -- the number of bits to shift. Must be >= 0.
1027 raise ValueError(
"Cannot shift by a negative amount.")
1029 raise ValueError(
"Cannot shift an empty bitstring.")
1030 n = min(n, self.
len)
1036 """Return bitstring with bits shifted by n to the right.
1038 n -- the number of bits to shift. Must be >= 0.
1042 raise ValueError(
"Cannot shift by a negative amount.")
1044 raise ValueError(
"Cannot shift an empty bitstring.")
1047 s = self.__class__(length=min(n, self.
len))
1048 s._append(self[:-n])
1052 """Return bitstring consisting of n concatenations of self.
1054 Called for expression of the form 'a = b*3'.
1055 n -- The number of concatenations. Must be >= 0.
1059 raise ValueError(
"Cannot multiply by a negative integer.")
1061 return self.__class__()
1067 """Return bitstring consisting of n concatenations of self.
1069 Called for expressions of the form 'a = 3*b'.
1070 n -- The number of concatenations. Must be >= 0.
1076 """Bit-wise 'and' between two bitstrings. Returns new bitstring.
1078 bs -- The bitstring to '&' with.
1080 Raises ValueError if the two bitstrings have differing lengths.
1084 if self.
len != bs.len:
1085 raise ValueError(
"Bitstrings must have the same length "
1092 """Bit-wise 'and' between two bitstrings. Returns new bitstring.
1094 bs -- the bitstring to '&' with.
1096 Raises ValueError if the two bitstrings have differing lengths.
1102 """Bit-wise 'or' between two bitstrings. Returns new bitstring.
1104 bs -- The bitstring to '|' with.
1106 Raises ValueError if the two bitstrings have differing lengths.
1110 if self.
len != bs.len:
1111 raise ValueError(
"Bitstrings must have the same length "
1118 """Bit-wise 'or' between two bitstrings. Returns new bitstring.
1120 bs -- The bitstring to '|' with.
1122 Raises ValueError if the two bitstrings have differing lengths.
1128 """Bit-wise 'xor' between two bitstrings. Returns new bitstring.
1130 bs -- The bitstring to '^' with.
1132 Raises ValueError if the two bitstrings have differing lengths.
1136 if self.
len != bs.len:
1137 raise ValueError(
"Bitstrings must have the same length "
1144 """Bit-wise 'xor' between two bitstrings. Returns new bitstring.
1146 bs -- The bitstring to '^' with.
1148 Raises ValueError if the two bitstrings have differing lengths.
1154 """Return whether bs is contained in the current bitstring.
1156 bs -- The bitstring to search for.
1162 except AttributeError:
1164 found = Bits.find(self, bs, bytealigned=
False)
1167 except AttributeError:
1172 """Return an integer hash of the object."""
1180 shorter = self[:80] + self[-80:]
1182 for byte
in shorter.tobytes():
1184 h = (h << 4) + ord(byte)
1192 return h % 1442968193
1196 """Return True if any bits are set to 1, otherwise return False."""
1197 return self.
any(
True)
1200 __bool__ = __nonzero__
1203 """Check internal self consistency as a debugging aid."""
1204 assert self.
len >= 0
1210 def _init_with_token(cls, name, token_length, value):
1211 if token_length
is not None:
1212 token_length = int(token_length)
1213 if token_length == 0:
1217 return cls(token_length)
1220 if token_length
is None:
1221 error =
"Token has no value ({0}=???).".format(name)
1223 error =
"Token has no value ({0}:{1}=???).".format(name, token_length)
1224 raise ValueError(error)
1226 b = cls(**{_tokenname_to_initialiser[name]: value})
1228 if name
in (
'se',
'ue',
'sie',
'uie'):
1229 b = cls(**{name: int(value)})
1230 elif name
in (
'uint',
'int',
'uintbe',
'intbe',
'uintle',
'intle',
'uintne',
'intne'):
1231 b = cls(**{name: int(value),
'length': token_length})
1232 elif name
in (
'float',
'floatbe',
'floatle',
'floatne'):
1233 b = cls(**{name: float(value),
'length': token_length})
1234 elif name ==
'bool':
1235 if value
in (1,
'True',
'1'):
1237 elif value
in (0,
'False',
'0'):
1240 raise CreationError(
"bool token can only be 'True' or 'False'.")
1243 if token_length
is not None and b.len != token_length:
1244 msg =
"Token with length {0} packed with value of length {1} ({2}:{3}={4})."
1245 raise CreationError(msg, token_length, b.len, name, token_length, value)
1249 """Reset the bitstring to an empty state."""
1253 """Set bitstring from a bitstring, file, bool, integer, array, iterable or string."""
1258 if isinstance(s, Bits):
1260 length = s.len - offset
1263 if isinstance(s, file):
1267 length = os.path.getsize(s.name) * 8 - offset
1268 byteoffset, offset = divmod(offset, 8)
1269 bytelength = (length + byteoffset * 8 + offset + 7) // 8 - byteoffset
1271 if length + byteoffset * 8 + offset > m.filelength * 8:
1272 raise CreationError(
"File is not long enough for specified "
1273 "length and offset.")
1276 if length
is not None:
1277 raise CreationError(
"The length keyword isn't applicable to this initialiser.")
1279 raise CreationError(
"The offset keyword isn't applicable to this initialiser.")
1280 if isinstance(s, basestring):
1282 assert bs._offset == 0
1285 if isinstance(s, (bytes, bytearray)):
1288 if isinstance(s, array.array):
1292 if isinstance(s, numbers.Integral):
1295 msg =
"Can't create bitstring of negative length {0}."
1297 data = bytearray((s + 7) // 8)
1300 if isinstance(s, collections.Iterable):
1304 raise TypeError(
"Cannot initialise bitstring from {0}.".format(type(s)))
1307 """Use file as source of bits."""
1308 source = open(filename,
'rb')
1312 length = os.path.getsize(source.name) * 8 - offset
1313 byteoffset, offset = divmod(offset, 8)
1314 bytelength = (length + byteoffset * 8 + offset + 7) // 8 - byteoffset
1316 if length + byteoffset * 8 + offset > m.filelength * 8:
1317 raise CreationError(
"File is not long enough for specified "
1318 "length and offset.")
1322 """Set the data from a string."""
1323 data = bytearray(data)
1326 length = len(data) * 8 - offset
1329 if length + offset > len(data) * 8:
1330 msg =
"Not enough data present. Need {0} bits, have {1}."
1338 """Unchecked version of _setbytes_safe."""
1343 """Read bytes and return them. Note that length is in bits."""
1344 assert length % 8 == 0
1345 assert start + length <= self.
len
1346 if not (start + self.
_offset) % 8:
1348 (start + self.
_offset + length) // 8))
1352 """Return the data as an ordinary string."""
1354 raise InterpretError(
"Cannot interpret as bytes unambiguously - "
1355 "not multiple of 8 bits.")
1359 """Reset the bitstring to have given unsigned int interpretation."""
1364 except AttributeError:
1368 if length
is None or length == 0:
1369 raise CreationError(
"A non-zero length must be specified with a "
1370 "uint initialiser.")
1371 if uint >= (1 << length):
1372 msg =
"{0} is too large an unsigned integer for a bitstring of length {1}. "\
1373 "The allowed range is [0, {2}]."
1376 raise CreationError(
"uint cannot be initialsed by a negative number.")
1382 data = bytes.fromhex(s)
1383 except AttributeError:
1385 data = binascii.unhexlify(s)
1387 extrabytes = ((length + 7) // 8) - len(data)
1389 data = b
'\x00' * extrabytes + data
1390 offset = 8 - (length % 8)
1396 """Read bits and interpret as an unsigned int."""
1401 startbyte = (start + offset) // 8
1402 endbyte = (start + offset + length - 1) // 8
1404 b = binascii.hexlify(bytes(self.
_datastore.getbyteslice(startbyte, endbyte + 1)))
1407 final_bits = 8 - ((start + offset + length) % 8)
1410 i &= (1 << length) - 1
1414 """Return data as an unsigned int."""
1418 """Reset the bitstring to have given signed int interpretation."""
1420 if length
is None and hasattr(self,
'len')
and self.
len != 0:
1422 if length
is None or length == 0:
1423 raise CreationError(
"A non-zero length must be specified with an int initialiser.")
1424 if int_ >= (1 << (length - 1))
or int_ < -(1 << (length - 1)):
1425 raise CreationError(
"{0} is too large a signed integer for a bitstring of length {1}. "
1426 "The allowed range is [{2}, {3}].", int_, length, -(1 << (length - 1)),
1427 (1 << (length - 1)) - 1)
1441 """Read bits and interpret as a signed int"""
1443 if not ui >> (length - 1):
1447 tmp = (~(ui - 1)) & ((1 << length) - 1)
1451 """Return data as a two's complement signed int."""
1455 """Set the bitstring to a big-endian unsigned int interpretation."""
1456 if length
is not None and length % 8 != 0:
1457 raise CreationError(
"Big-endian integers must be whole-byte. "
1458 "Length = {0} bits.", length)
1462 """Read bits and interpret as a big-endian unsigned int."""
1465 "Length = {0} bits.", length)
1469 """Return data as a big-endian two's complement unsigned int."""
1473 """Set bitstring to a big-endian signed int interpretation."""
1474 if length
is not None and length % 8 != 0:
1475 raise CreationError(
"Big-endian integers must be whole-byte. "
1476 "Length = {0} bits.", length)
1480 """Read bits and interpret as a big-endian signed int."""
1483 "Length = {0} bits.", length)
1484 return self.
_readint(length, start)
1487 """Return data as a big-endian two's complement signed int."""
1490 def _setuintle(self, uintle, length=None):
1491 if length
is not None and length % 8 != 0:
1492 raise CreationError(
"Little-endian integers must be whole-byte. "
1493 "Length = {0} bits.", length)
1498 """Read bits and interpret as a little-endian unsigned int."""
1500 raise InterpretError(
"Little-endian integers must be whole-byte. "
1501 "Length = {0} bits.", length)
1502 assert start + length <= self.
len
1503 absolute_pos = start + self.
_offset
1504 startbyte, offset = divmod(absolute_pos, 8)
1507 endbyte = (absolute_pos + length - 1) // 8
1509 while endbyte - chunksize + 1 >= startbyte:
1510 val <<= 8 * chunksize
1511 val += struct.unpack(
'<L', bytes(self.
_datastore.getbyteslice(endbyte + 1 - chunksize, endbyte + 1)))[0]
1512 endbyte -= chunksize
1513 for b
in xrange(endbyte, startbyte - 1, -1):
1517 data = self.
_slice(start, start + length)
1518 assert data.len % 8 == 0
1519 data._reversebytes(0, self.
len)
1520 for b
in bytearray(data.bytes):
1525 def _getuintle(self):
1528 def _setintle(self, intle, length=None):
1529 if length
is not None and length % 8 != 0:
1530 raise CreationError(
"Little-endian integers must be whole-byte. "
1531 "Length = {0} bits.", length)
1536 """Read bits and interpret as a little-endian signed int."""
1538 if not ui >> (length - 1):
1542 tmp = (~(ui - 1)) & ((1 << length) - 1)
1545 def _getintle(self):
1548 def _setfloat(self, f, length=None):
1550 if length
is None and hasattr(self,
'len')
and self.
len != 0:
1552 if length
is None or length == 0:
1553 raise CreationError(
"A non-zero length must be specified with a "
1554 "float initialiser.")
1556 b = struct.pack(
'>f', f)
1558 b = struct.pack(
'>d', f)
1560 raise CreationError(
"floats can only be 32 or 64 bits long, "
1561 "not {0} bits", length)
1565 """Read bits and interpret as a float."""
1566 if not (start + self.
_offset) % 8:
1567 startbyte = (start + self.
_offset) // 8
1569 f, = struct.unpack(
'>f', bytes(self.
_datastore.getbyteslice(startbyte, startbyte + 4)))
1571 f, = struct.unpack(
'>d', bytes(self.
_datastore.getbyteslice(startbyte, startbyte + 8)))
1574 f, = struct.unpack(
'>f', self.
_readbytes(32, start))
1576 f, = struct.unpack(
'>d', self.
_readbytes(64, start))
1580 raise InterpretError(
"floats can only be 32 or 64 bits long, not {0} bits", length)
1583 """Interpret the whole bitstring as a float."""
1586 def _setfloatle(self, f, length=None):
1588 if length
is None and hasattr(self,
'len')
and self.
len != 0:
1590 if length
is None or length == 0:
1591 raise CreationError(
"A non-zero length must be specified with a "
1592 "float initialiser.")
1594 b = struct.pack(
'<f', f)
1596 b = struct.pack(
'<d', f)
1598 raise CreationError(
"floats can only be 32 or 64 bits long, "
1599 "not {0} bits", length)
1603 """Read bits and interpret as a little-endian float."""
1604 startbyte, offset = divmod(start + self.
_offset, 8)
1607 f, = struct.unpack(
'<f', bytes(self.
_datastore.getbyteslice(startbyte, startbyte + 4)))
1609 f, = struct.unpack(
'<d', bytes(self.
_datastore.getbyteslice(startbyte, startbyte + 8)))
1612 f, = struct.unpack(
'<f', self.
_readbytes(32, start))
1614 f, = struct.unpack(
'<d', self.
_readbytes(64, start))
1619 "not {0} bits", length)
1622 """Interpret the whole bitstring as a little-endian float."""
1626 """Initialise bitstring with unsigned exponential-Golomb code for integer i.
1628 Raises CreationError if i < 0.
1632 raise CreationError(
"Cannot use negative initialiser for unsigned "
1633 "exponential-Golomb.")
1642 remainingpart = i + 1 - (1 << leadingzeros)
1643 binstring =
'0' * leadingzeros +
'1' +
Bits(uint=remainingpart,
1644 length=leadingzeros).bin
1648 """Return interpretation of next bits as unsigned exponential-Golomb code.
1650 Raises ReadError if the end of the bitstring is encountered while
1656 while not self[pos]:
1659 raise ReadError(
"Read off end of bitstring trying to read code.")
1660 leadingzeros = pos - oldpos
1661 codenum = (1 << leadingzeros) - 1
1662 if leadingzeros > 0:
1663 if pos + leadingzeros + 1 > self.
len:
1664 raise ReadError(
"Read off end of bitstring trying to read code.")
1665 codenum += self.
_readuint(leadingzeros, pos + 1)
1666 pos += leadingzeros + 1
1673 """Return data as unsigned exponential-Golomb code.
1675 Raises InterpretError if bitstring is not a single exponential-Golomb code.
1679 value, newpos = self.
_readue(0)
1680 if value
is None or newpos != self.
len:
1683 raise InterpretError(
"Bitstring is not a single exponential-Golomb code.")
1687 """Initialise bitstring with signed exponential-Golomb code for integer i."""
1695 """Return data as signed exponential-Golomb code.
1697 Raises InterpretError if bitstring is not a single exponential-Golomb code.
1701 value, newpos = self.
_readse(0)
1702 if value
is None or newpos != self.
len:
1705 raise InterpretError(
"Bitstring is not a single exponential-Golomb code.")
1709 """Return interpretation of next bits as a signed exponential-Golomb code.
1711 Advances position to after the read code.
1713 Raises ReadError if the end of the bitstring is encountered while
1717 codenum, pos = self.
_readue(pos)
1718 m = (codenum + 1) // 2
1725 """Initialise bitstring with unsigned interleaved exponential-Golomb code for integer i.
1727 Raises CreationError if i < 0.
1731 raise CreationError(
"Cannot use negative initialiser for unsigned "
1732 "interleaved exponential-Golomb.")
1736 """Return interpretation of next bits as unsigned interleaved exponential-Golomb code.
1738 Raises ReadError if the end of the bitstring is encountered while
1744 while not self[pos]:
1747 codenum += self[pos]
1751 raise ReadError(
"Read off end of bitstring trying to read code.")
1756 """Return data as unsigned interleaved exponential-Golomb code.
1758 Raises InterpretError if bitstring is not a single exponential-Golomb code.
1763 if value
is None or newpos != self.
len:
1766 raise InterpretError(
"Bitstring is not a single interleaved exponential-Golomb code.")
1770 """Initialise bitstring with signed interleaved exponential-Golomb code for integer i."""
1778 """Return data as signed interleaved exponential-Golomb code.
1780 Raises InterpretError if bitstring is not a single exponential-Golomb code.
1785 if value
is None or newpos != self.
len:
1788 raise InterpretError(
"Bitstring is not a single interleaved exponential-Golomb code.")
1792 """Return interpretation of next bits as a signed interleaved exponential-Golomb code.
1794 Advances position to after the read code.
1796 Raises ReadError if the end of the bitstring is encountered while
1805 return -codenum, pos + 1
1807 return codenum, pos + 1
1809 raise ReadError(
"Read off end of bitstring trying to read code.")
1811 def _setbool(self, value):
1814 if value
in (1,
'True'):
1816 elif value
in (0,
'False'):
1819 raise CreationError(
'Cannot initialise boolean with {0}.', value)
1823 msg =
"For a bool interpretation a bitstring must be 1 bit long, not {0} bits."
1827 def _readbool(self, pos):
1828 return self[pos], pos + 1
1831 """Reset the bitstring to the value given in binstring."""
1834 binstring = binstring.replace(
'0b',
'')
1838 """Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'."""
1839 length = len(binstring)
1841 boundary = ((length + 7) // 8) * 8
1842 padded_binstring = binstring +
'0' * (boundary - length)\
1843 if len(binstring) < boundary
else binstring
1845 bytelist = [int(padded_binstring[x:x + 8], 2)
1846 for x
in xrange(0, len(padded_binstring), 8)]
1848 raise CreationError(
"Invalid character in bin initialiser {0}.", binstring)
1852 """Read bits and interpret as a binary string."""
1856 startbyte, startoffset = divmod(start + self.
_offset, 8)
1857 endbyte = (start + self.
_offset + length - 1) // 8
1858 b = self.
_datastore.getbyteslice(startbyte, endbyte + 1)
1861 c =
"{:0{}b}".format(int(binascii.hexlify(b), 16), 8 * len(b))
1864 c =
"{0:0{1}b}".format(int(binascii.hexlify(str(b)), 16), 8 * len(b))
1866 return c[startoffset:startoffset + length]
1869 """Return interpretation as a binary string."""
1873 """Reset the bitstring to have the value given in octstring."""
1876 octstring = octstring.replace(
'0o',
'')
1880 if not 0 <= int(i) < 8:
1882 binlist.append(OCT_TO_BITS[int(i)])
1884 raise CreationError(
"Invalid symbol '{0}' in oct initialiser.", i)
1888 """Read bits and interpret as an octal string."""
1891 "not multiple of 3 bits.")
1896 end = oct(self.
_readuint(length, start))[LEADING_OCT_CHARS:]
1897 if end.endswith(
'L'):
1899 middle =
'0' * (length // 3 - len(end))
1903 """Return interpretation as an octal string."""
1907 """Reset the bitstring to have the value given in hexstring."""
1910 hexstring = hexstring.replace(
'0x',
'')
1911 length = len(hexstring)
1916 data = bytearray.fromhex(hexstring)
1919 data = bytearray.fromhex(unicode(hexstring))
1925 """Read bits and interpret as a hex string."""
1928 "not multiple of 4 bits.")
1934 except AttributeError:
1937 s = str(binascii.hexlify(s).decode(
'utf-8'))
1939 return s[:-1]
if (length // 4) % 2
else s
1942 """Return the hexadecimal representation as a string prefixed with '0x'.
1944 Raises an InterpretError if the bitstring's length is not a multiple of 4.
1949 def _getoffset(self):
1953 """Return the length of the bitstring in bits."""
1957 """Ensure the data is held in memory, not in a file."""
1963 """Convert bs to a bitstring and return it.
1965 offset gives the suggested bit offset of first significant
1966 bit, to optimise append etc.
1969 if isinstance(bs, Bits):
1972 return cache[(bs, offset)]
1974 if isinstance(bs, basestring):
1978 except ValueError
as e:
1981 b._append(Bits._init_with_token(*tokens[0]))
1982 b._datastore =
offsetcopy(b._datastore, offset)
1983 for token
in tokens[1:]:
1984 b._append(Bits._init_with_token(*token))
1985 assert b._assertsanity()
1986 assert b.len == 0
or b._offset == offset
1987 if len(cache) < CACHE_SIZE:
1988 cache[(bs, offset)] = b
1996 """Create and return a new copy of the Bits (always in memory)."""
1997 s_copy = self.__class__()
2003 """Used internally to get a slice, without error checking."""
2005 return self.__class__()
2007 startbyte, newoffset = divmod(start + offset, 8)
2008 endbyte = (end + offset - 1) // 8
2009 bs = self.__class__()
2010 bs._setbytes_unsafe(self.
_datastore.getbyteslice(startbyte, endbyte + 1), end - start, newoffset)
2014 """Reads a token from the bitstring and returns the result."""
2015 if length
is not None and int(length) > self.
length - pos:
2016 raise ReadError(
"Reading off the end of the data. "
2017 "Tried to read {0} bits when only {1} available.".format(int(length), self.
length - pos))
2019 val = name_to_read[name](self, length, pos)
2020 return val, pos + length
2023 return None, pos + length
2024 raise ValueError(
"Can't parse token {0}:{1}".format(name, length))
2027 return name_to_read[name](self, pos)
2030 """Append a bitstring to the current bitstring."""
2034 """Prepend a bitstring to the current bitstring."""
2038 """Reverse all bits in-place."""
2040 n = [BYTE_REVERSAL_DICT[b]
for b
in self.
_datastore.rawbytes]
2044 newoffset = 8 - (self.
_offset + self.
len) % 8
2050 """Truncate bits from the start of the bitstring."""
2051 assert 0 <= bits <= self.
len
2054 if bits == self.
len:
2057 bytepos, offset = divmod(self.
_offset + bits, 8)
2063 """Truncate bits from the end of the bitstring."""
2064 assert 0 <= bits <= self.
len
2067 if bits == self.
len:
2070 newlength_in_bytes = (self.
_offset + self.
len - bits + 7) // 8
2076 """Insert bs at pos."""
2077 assert 0 <= pos <= self.
len
2078 if pos > self.
len // 2:
2086 start = self.
_slice(0, pos)
2091 self.
_pos = pos + bs.len
2092 except AttributeError:
2097 """Overwrite with bs at pos."""
2098 assert 0 <= pos < self.
len
2103 firstbytepos = (self.
_offset + pos) // 8
2104 lastbytepos = (self.
_offset + pos + bs.len - 1) // 8
2105 bytepos, bitoffset = divmod(self.
_offset + pos, 8)
2106 if firstbytepos == lastbytepos:
2107 mask = ((1 << bs.len) - 1) << (8 - bs.len - bitoffset)
2113 mask = (1 << (8 - bitoffset)) - 1
2118 self.
_datastore.setbyteslice(firstbytepos + 1, lastbytepos, d.getbyteslice(1, lastbytepos - firstbytepos))
2120 bitsleft = (self.
_offset + pos + bs.len) % 8
2123 mask = (1 << (8 - bitsleft)) - 1
2126 self.
_datastore.getbyte(lastbytepos) | (d.getbyte(d.bytelength - 1) & ~mask))
2130 """Delete bits at pos."""
2131 assert 0 <= pos <= self.
len
2132 assert pos + bits <= self.
len
2137 if pos + bits == self.
len:
2141 if pos > self.
len - pos - bits:
2145 assert self.
len - pos > 0
2150 start = self.
_slice(0, pos)
2156 """Reverse bytes in-place."""
2159 newoffset = 8 - (start % 8)
2164 toreverse = bytearray(self.
_datastore.getbyteslice((newoffset + start) // 8, (newoffset + end) // 8))
2166 self.
_datastore.setbyteslice((newoffset + start) // 8, (newoffset + end) // 8, toreverse)
2169 """Set bit at pos to 1."""
2170 assert 0 <= pos < self.
len
2174 """Set bit at pos to 0."""
2175 assert 0 <= pos < self.
len
2179 """Flip bit at pos 1<->0."""
2180 assert 0 <= pos < self.
len
2184 """Invert every bit."""
2188 set(p, 256 + ~get(p))
2191 """Shift bits by n to the left in place. Return self."""
2192 assert 0 < n <= self.
len
2198 """Shift bits by n to the right in place. Return self."""
2199 assert 0 < n <= self.
len
2205 """Concatenate n copies of self in place. Return self."""
2215 self.
_append(self[0:(n - m) * old_len])
2219 """Helper function containing most of the __ior__, __iand__, __ixor__ code."""
2221 self_byteoffset, self_bitoffset = divmod(self.
_offset, 8)
2222 bs_byteoffset, bs_bitoffset = divmod(bs._offset, 8)
2223 if bs_bitoffset != self_bitoffset:
2224 if not self_bitoffset:
2229 b = bs._datastore.rawbytes
2230 for i
in xrange(len(a)):
2231 a[i] = f(a[i + self_byteoffset], b[i + bs_byteoffset])
2237 def _iand(self, bs):
2240 def _ixor(self, bs):
2244 """Read some bits from the bitstring and return newly constructed bitstring."""
2245 return self.
_slice(start, start + length)
2248 """Validate start and end and return them as positive bit positions."""
2257 if not 0 <= end <= self.
len:
2258 raise ValueError(
"end is not a valid position in the bitstring.")
2259 if not 0 <= start <= self.
len:
2260 raise ValueError(
"start is not a valid position in the bitstring.")
2262 raise ValueError(
"end must not be less than start.")
2266 """Interpret the whole bitstring using fmt and return list.
2268 fmt -- A single string or a list of strings with comma separated tokens
2269 describing how to interpret the bits in the bitstring. Items
2270 can also be integers, for reading new bitstring of the given length.
2271 kwargs -- A dictionary or keyword-value pairs - the keywords used in the
2272 format string will be replaced with their given value.
2274 Raises ValueError if the format is not understood. If not enough bits
2275 are available then all bits to the end of the bitstring will be used.
2277 See the docstring for 'read' for token examples.
2280 return self.
_readlist(fmt, 0, **kwargs)[0]
2282 def _readlist(self, fmt, pos, **kwargs):
2284 stretchy_token =
None
2285 if isinstance(fmt, basestring):
2289 for i, f
in enumerate(fmt):
2290 if isinstance(f, numbers.Integral):
2291 fmt[i] =
"bits:{0}".format(f)
2293 stretchy, tkns =
tokenparser(f_item, tuple(sorted(kwargs.keys())))
2296 raise Error(
"It's not possible to have more than one 'filler' token.")
2297 stretchy_token = stretchy
2299 if not stretchy_token:
2301 for name, length, _
in tokens:
2302 if length
in kwargs:
2303 length = kwargs[length]
2306 if name
in kwargs
and length
is None:
2308 value, pos = self.
_readtoken(
'uint', pos, kwargs[name])
2311 value, pos = self.
_readtoken(name, pos, length)
2312 if value
is not None:
2315 stretchy_token =
False
2316 bits_after_stretchy_token = 0
2317 for token
in tokens:
2318 name, length, _ = token
2319 if length
in kwargs:
2320 length = kwargs[length]
2323 if name
in kwargs
and length
is None:
2325 length = kwargs[name]
2327 if name
in (
'se',
'ue',
'sie',
'uie'):
2328 raise Error(
"It's not possible to parse a variable"
2329 "length token after a 'filler' token.")
2332 raise Error(
"It's not possible to have more than "
2333 "one 'filler' token.")
2334 bits_after_stretchy_token += length
2335 if length
is None and name
not in (
'se',
'ue',
'sie',
'uie'):
2336 assert not stretchy_token
2337 stretchy_token = token
2338 bits_left = self.
len - pos
2340 for token
in tokens:
2341 name, length, _ = token
2342 if token
is stretchy_token:
2344 length = max(bits_left - bits_after_stretchy_token, 0)
2345 if length
in kwargs:
2346 length = kwargs[length]
2349 if name
in kwargs
and length
is None:
2351 length = kwargs[name]
2352 if length
is not None:
2354 value, pos = self.
_readtoken(name, pos, length)
2355 if value
is not None:
2356 return_values.append(value)
2357 return return_values, pos
2360 """Quicker version of find when everything's whole byte
2365 assert bytealigned
is True
2367 bytepos = (start + 7) // 8
2371 increment = max(1024, len(bytes_) * 10)
2372 buffersize = increment + len(bytes_)
2375 buf = bytearray(self.
_datastore.getbyteslice(p, min(p + buffersize, finalpos)))
2376 pos = buf.find(bytes_)
2387 """Find first occurrence of a compiled regular expression.
2389 Note that this doesn't support arbitrary regexes, in particular they
2390 must match a known length.
2394 length = len(reg_ex.pattern)
2397 increment = max(4096, length * 10)
2398 buffersize = increment + length
2400 buf = self.
_readbin(min(buffersize, end - p), p)
2402 m = reg_ex.search(buf)
2408 if not bytealigned
or (p + pos) % 8 == 0:
2418 def find(self, bs, start=None, end=None, bytealigned=None):
2419 """Find first occurrence of substring bs.
2421 Returns a single item tuple with the bit position if found, or an
2422 empty tuple if not found. The bit position (pos property) will
2423 also be set to the start of the substring if it is found.
2425 bs -- The bitstring to find.
2426 start -- The bit position to start the search. Defaults to 0.
2427 end -- The bit position one past the last bit to search.
2428 Defaults to self.len.
2429 bytealigned -- If True the bitstring will only be
2430 found on byte boundaries.
2432 Raises ValueError if bs is empty, if start < 0, if end > self.len or
2435 >>> BitArray('0xc3e').find('0b1111')
2441 raise ValueError(
"Cannot find an empty bitstring.")
2443 if bytealigned
is None:
2444 bytealigned = globals()[
'bytealigned']
2445 if bytealigned
and not bs.len % 8
and not self.
_datastore.offset:
2446 p = self.
_findbytes(bs.bytes, start, end, bytealigned)
2448 p = self.
_findregex(re.compile(bs._getbin()), start, end, bytealigned)
2452 except (AttributeError, IndexError):
2456 def findall(self, bs, start=None, end=None, count=None, bytealigned=None):
2457 """Find all occurrences of bs. Return generator of bit positions.
2459 bs -- The bitstring to find.
2460 start -- The bit position to start the search. Defaults to 0.
2461 end -- The bit position one past the last bit to search.
2462 Defaults to self.len.
2463 count -- The maximum number of occurrences to find.
2464 bytealigned -- If True the bitstring will only be found on
2467 Raises ValueError if bs is empty, if start < 0, if end > self.len or
2470 Note that all occurrences of bs are found, even if they overlap.
2473 if count
is not None and count < 0:
2474 raise ValueError(
"In findall, count must be >= 0.")
2477 if bytealigned
is None:
2478 bytealigned = globals()[
'bytealigned']
2480 if bytealigned
and not bs.len % 8
and not self.
_datastore.offset:
2486 x = re.compile(bs._getbin())
2489 p = f(x, start, end, bytealigned)
2492 if count
is not None and c >= count:
2497 except AttributeError:
2508 def rfind(self, bs, start=None, end=None, bytealigned=None):
2509 """Find final occurrence of substring bs.
2511 Returns a single item tuple with the bit position if found, or an
2512 empty tuple if not found. The bit position (pos property) will
2513 also be set to the start of the substring if it is found.
2515 bs -- The bitstring to find.
2516 start -- The bit position to end the reverse search. Defaults to 0.
2517 end -- The bit position one past the first bit to reverse search.
2518 Defaults to self.len.
2519 bytealigned -- If True the bitstring will only be found on byte
2522 Raises ValueError if bs is empty, if start < 0, if end > self.len or
2528 if bytealigned
is None:
2529 bytealigned = globals()[
'bytealigned']
2531 raise ValueError(
"Cannot find an empty bitstring.")
2534 increment = max(8192, bs.len * 80)
2535 buffersize = min(increment + bs.len, end - start)
2536 pos = max(start, end - buffersize)
2538 found = list(self.
findall(bs, start=pos, end=pos + buffersize,
2539 bytealigned=bytealigned))
2543 pos = max(start, pos - increment)
2547 def cut(self, bits, start=None, end=None, count=None):
2548 """Return bitstring generator by cutting into bits sized chunks.
2550 bits -- The size in bits of the bitstring chunks to generate.
2551 start -- The bit position to start the first cut. Defaults to 0.
2552 end -- The bit position one past the last bit to use in the cut.
2553 Defaults to self.len.
2554 count -- If specified then at most count items are generated.
2555 Default is to cut as many times as possible.
2559 if count
is not None and count < 0:
2560 raise ValueError(
"Cannot cut - count must be >= 0.")
2562 raise ValueError(
"Cannot cut - bits must be >= 0.")
2564 while count
is None or c < count:
2566 nextchunk = self.
_slice(start, min(start + bits, end))
2567 if nextchunk.len != bits:
2569 assert nextchunk._assertsanity()
2574 def split(self, delimiter, start=None, end=None, count=None,
2576 """Return bitstring generator by splittling using a delimiter.
2578 The first item returned is the initial bitstring before the delimiter,
2579 which may be an empty bitstring.
2581 delimiter -- The bitstring used as the divider.
2582 start -- The bit position to start the split. Defaults to 0.
2583 end -- The bit position one past the last bit to use in the split.
2584 Defaults to self.len.
2585 count -- If specified then at most count items are generated.
2586 Default is to split as many times as possible.
2587 bytealigned -- If True splits will only occur on byte boundaries.
2589 Raises ValueError if the delimiter is empty.
2592 delimiter =
Bits(delimiter)
2593 if not delimiter.len:
2594 raise ValueError(
"split delimiter cannot be empty.")
2596 if bytealigned
is None:
2597 bytealigned = globals()[
'bytealigned']
2598 if count
is not None and count < 0:
2599 raise ValueError(
"Cannot split - count must be >= 0.")
2602 if bytealigned
and not delimiter.len % 8
and not self.
_datastore.offset:
2605 x = delimiter._getbytes()
2608 x = re.compile(delimiter._getbin())
2609 found = f(x, start, end, bytealigned)
2612 yield self.
_slice(start, end)
2615 yield self.
_slice(start, found[0])
2616 startpos = pos = found[0]
2618 while count
is None or c < count:
2619 pos += delimiter.len
2620 found = f(x, pos, end, bytealigned)
2623 yield self.
_slice(startpos, end)
2626 yield self.
_slice(startpos, found[0])
2627 startpos = pos = found[0]
2632 """Return concatenation of bitstrings joined by self.
2634 sequence -- A sequence of bitstrings.
2637 s = self.__class__()
2640 s._append(
Bits(next(i)))
2645 except StopIteration:
2650 """Return the bitstring as bytes, padding with zero bits if needed.
2652 Up to seven zero bits will be added at the end to byte align.
2657 unusedbits = 8 - self.
len % 8
2659 d[-1] &= (0xff << unusedbits)
2663 """Write the bitstring to a file object, padding with zero bits if needed.
2665 Up to seven zero bits will be added at the end to byte align.
2670 chunksize = 1024 * 1024
2674 p = self.
_datastore.getbyteslice(a, min(a + chunksize, bytelen - 1))
2675 while len(p) == chunksize:
2678 p = self.
_datastore.getbyteslice(a, min(a + chunksize, bytelen - 1))
2681 bits_in_final_byte = self.
len % 8
2682 if not bits_in_final_byte:
2683 bits_in_final_byte = 8
2684 f.write(self[-bits_in_final_byte:].
tobytes())
2688 b = a + chunksize * 8
2689 while b <= self.
len:
2697 """Return whether the current bitstring starts with prefix.
2699 prefix -- The bitstring to search for.
2700 start -- The bit position to start from. Defaults to 0.
2701 end -- The bit position to end at. Defaults to self.len.
2704 prefix =
Bits(prefix)
2706 if end < start + prefix.len:
2708 end = start + prefix.len
2709 return self.
_slice(start, end) == prefix
2712 """Return whether the current bitstring ends with suffix.
2714 suffix -- The bitstring to search for.
2715 start -- The bit position to start from. Defaults to 0.
2716 end -- The bit position to end at. Defaults to self.len.
2719 suffix =
Bits(suffix)
2721 if start + suffix.len > end:
2723 start = end - suffix.len
2724 return self.
_slice(start, end) == suffix
2726 def all(self, value, pos=None):
2727 """Return True if one or many bits are all set to value.
2729 value -- If value is True then checks for bits set to 1, otherwise
2730 checks for bits set to 0.
2731 pos -- An iterable of bit positions. Negative numbers are treated in
2732 the same way as slice indices. Defaults to the whole bitstring.
2738 pos = xrange(self.
len)
2742 if not 0 <= p < length:
2743 raise IndexError(
"Bit position {0} out of range.".format(p))
2748 def any(self, value, pos=None):
2749 """Return True if any of one or many bits are set to value.
2751 value -- If value is True then checks for bits set to 1, otherwise
2752 checks for bits set to 0.
2753 pos -- An iterable of bit positions. Negative numbers are treated in
2754 the same way as slice indices. Defaults to the whole bitstring.
2760 pos = xrange(self.
len)
2764 if not 0 <= p < length:
2765 raise IndexError(
"Bit position {0} out of range.".format(p))
2771 """Return count of total number of either zero or one bits.
2773 value -- If True then bits set to 1 are counted, otherwise bits set
2776 >>> Bits('0xef').count(1)
2784 count = sum(BIT_COUNT[self.
_datastore.getbyte(i)]
for i
in xrange(self.
_datastore.bytelength - 1))
2791 return count
if value
else self.
len - count
2794 if byteorder ==
'little':
2795 _setfloatne = _setfloatle
2796 _readfloatne = _readfloatle
2797 _getfloatne = _getfloatle
2798 _setuintne = _setuintle
2799 _readuintne = _readuintle
2800 _getuintne = _getuintle
2801 _setintne = _setintle
2802 _readintne = _readintle
2803 _getintne = _getintle
2805 _setfloatne = _setfloat
2806 _readfloatne = _readfloat
2807 _getfloatne = _getfloat
2808 _setuintne = _setuintbe
2809 _readuintne = _readuintbe
2810 _getuintne = _getuintbe
2811 _setintne = _setintbe
2812 _readintne = _readintbe
2813 _getintne = _getintbe
2815 _offset = property(_getoffset)
2817 len = property(_getlength,
2818 doc=
"""The length of the bitstring in bits. Read only.
2820 length = property(_getlength,
2821 doc=
"""The length of the bitstring in bits. Read only.
2823 bool = property(_getbool,
2824 doc=
"""The bitstring as a bool (True or False). Read only.
2826 hex = property(_gethex,
2827 doc=
"""The bitstring as a hexadecimal string. Read only.
2829 bin = property(_getbin,
2830 doc=
"""The bitstring as a binary string. Read only.
2832 oct = property(_getoct,
2833 doc=
"""The bitstring as an octal string. Read only.
2835 bytes = property(_getbytes,
2836 doc=
"""The bitstring as a bytes object. Read only.
2838 int = property(_getint,
2839 doc=
"""The bitstring as a two's complement signed int. Read only.
2841 uint = property(_getuint,
2842 doc=
"""The bitstring as a two's complement unsigned int. Read only.
2844 float = property(_getfloat,
2845 doc=
"""The bitstring as a floating point number. Read only.
2847 intbe = property(_getintbe,
2848 doc=
"""The bitstring as a two's complement big-endian signed int. Read only.
2850 uintbe = property(_getuintbe,
2851 doc=
"""The bitstring as a two's complement big-endian unsigned int. Read only.
2853 floatbe = property(_getfloat,
2854 doc=
"""The bitstring as a big-endian floating point number. Read only.
2856 intle = property(_getintle,
2857 doc=
"""The bitstring as a two's complement little-endian signed int. Read only.
2859 uintle = property(_getuintle,
2860 doc=
"""The bitstring as a two's complement little-endian unsigned int. Read only.
2862 floatle = property(_getfloatle,
2863 doc=
"""The bitstring as a little-endian floating point number. Read only.
2865 intne = property(_getintne,
2866 doc=
"""The bitstring as a two's complement native-endian signed int. Read only.
2868 uintne = property(_getuintne,
2869 doc=
"""The bitstring as a two's complement native-endian unsigned int. Read only.
2871 floatne = property(_getfloatne,
2872 doc=
"""The bitstring as a native-endian floating point number. Read only.
2874 ue = property(_getue,
2875 doc=
"""The bitstring as an unsigned exponential-Golomb code. Read only.
2877 se = property(_getse,
2878 doc=
"""The bitstring as a signed exponential-Golomb code. Read only.
2880 uie = property(_getuie,
2881 doc=
"""The bitstring as an unsigned interleaved exponential-Golomb code. Read only.
2883 sie = property(_getsie,
2884 doc=
"""The bitstring as a signed interleaved exponential-Golomb code. Read only.
2889 name_to_read = {
'uint': Bits._readuint,
2890 'uintle': Bits._readuintle,
2891 'uintbe': Bits._readuintbe,
2892 'uintne': Bits._readuintne,
2893 'int': Bits._readint,
2894 'intle': Bits._readintle,
2895 'intbe': Bits._readintbe,
2896 'intne': Bits._readintne,
2897 'float': Bits._readfloat,
2898 'floatbe': Bits._readfloat,
2899 'floatle': Bits._readfloatle,
2900 'floatne': Bits._readfloatne,
2901 'hex': Bits._readhex,
2902 'oct': Bits._readoct,
2903 'bin': Bits._readbin,
2904 'bits': Bits._readbits,
2905 'bytes': Bits._readbytes,
2908 'uie': Bits._readuie,
2909 'sie': Bits._readsie,
2910 'bool': Bits._readbool,
2914 init_with_length_and_offset = {
'bytes': Bits._setbytes_safe,
2915 'filename': Bits._setfile,
2918 init_with_length_only = {
'uint': Bits._setuint,
2919 'int': Bits._setint,
2920 'float': Bits._setfloat,
2921 'uintbe': Bits._setuintbe,
2922 'intbe': Bits._setintbe,
2923 'floatbe': Bits._setfloat,
2924 'uintle': Bits._setuintle,
2925 'intle': Bits._setintle,
2926 'floatle': Bits._setfloatle,
2927 'uintne': Bits._setuintne,
2928 'intne': Bits._setintne,
2929 'floatne': Bits._setfloatne,
2932 init_without_length_or_offset = {
'bin': Bits._setbin_safe,
2933 'hex': Bits._sethex,
2934 'oct': Bits._setoct,
2937 'uie': Bits._setuie,
2938 'sie': Bits._setsie,
2939 'bool': Bits._setbool,
2944 """A container holding a mutable sequence of bits.
2946 Subclass of the immutable Bits class. Inherits all of its
2947 methods (except __hash__) and adds mutating methods.
2951 append() -- Append a bitstring.
2952 byteswap() -- Change byte endianness in-place.
2953 insert() -- Insert a bitstring.
2954 invert() -- Flip bit(s) between one and zero.
2955 overwrite() -- Overwrite a section with a new bitstring.
2956 prepend() -- Prepend a bitstring.
2957 replace() -- Replace occurrences of one bitstring with another.
2958 reverse() -- Reverse bits in-place.
2959 rol() -- Rotate bits to the left.
2960 ror() -- Rotate bits to the right.
2961 set() -- Set bit(s) to 1 or 0.
2963 Methods inherited from Bits:
2965 all() -- Check if all specified bits are set to 1 or 0.
2966 any() -- Check if any of specified bits are set to 1 or 0.
2967 count() -- Count the number of bits set to 1 or 0.
2968 cut() -- Create generator of constant sized chunks.
2969 endswith() -- Return whether the bitstring ends with a sub-string.
2970 find() -- Find a sub-bitstring in the current bitstring.
2971 findall() -- Find all occurrences of a sub-bitstring in the current bitstring.
2972 join() -- Join bitstrings together using current bitstring.
2973 rfind() -- Seek backwards to find a sub-bitstring.
2974 split() -- Create generator of chunks split by a delimiter.
2975 startswith() -- Return whether the bitstring starts with a sub-bitstring.
2976 tobytes() -- Return bitstring as bytes, padding if needed.
2977 tofile() -- Write bitstring to file, padding if needed.
2978 unpack() -- Interpret bits using format string.
2982 Mutating operators are available: [], <<=, >>=, +=, *=, &=, |= and ^=
2983 in addition to the inherited [], ==, !=, +, *, ~, <<, >>, &, | and ^.
2987 bin -- The bitstring as a binary string.
2988 bool -- For single bit bitstrings, interpret as True or False.
2989 bytepos -- The current byte position in the bitstring.
2990 bytes -- The bitstring as a bytes object.
2991 float -- Interpret as a floating point number.
2992 floatbe -- Interpret as a big-endian floating point number.
2993 floatle -- Interpret as a little-endian floating point number.
2994 floatne -- Interpret as a native-endian floating point number.
2995 hex -- The bitstring as a hexadecimal string.
2996 int -- Interpret as a two's complement signed integer.
2997 intbe -- Interpret as a big-endian signed integer.
2998 intle -- Interpret as a little-endian signed integer.
2999 intne -- Interpret as a native-endian signed integer.
3000 len -- Length of the bitstring in bits.
3001 oct -- The bitstring as an octal string.
3002 pos -- The current bit position in the bitstring.
3003 se -- Interpret as a signed exponential-Golomb code.
3004 ue -- Interpret as an unsigned exponential-Golomb code.
3005 sie -- Interpret as a signed interleaved exponential-Golomb code.
3006 uie -- Interpret as an unsigned interleaved exponential-Golomb code.
3007 uint -- Interpret as a two's complement unsigned integer.
3008 uintbe -- Interpret as a big-endian unsigned integer.
3009 uintle -- Interpret as a little-endian unsigned integer.
3010 uintne -- Interpret as a native-endian unsigned integer.
3019 def __init__(self, auto=None, length=None, offset=None, **kwargs):
3020 """Either specify an 'auto' initialiser:
3021 auto -- a string of comma separated tokens, an integer, a file object,
3022 a bytearray, a boolean iterable or another bitstring.
3024 Or initialise via **kwargs with one (and only one) of:
3025 bytes -- raw data as a string, for example read from a binary file.
3026 bin -- binary string representation, e.g. '0b001010'.
3027 hex -- hexadecimal string representation, e.g. '0x2ef'
3028 oct -- octal string representation, e.g. '0o777'.
3029 uint -- an unsigned integer.
3030 int -- a signed integer.
3031 float -- a floating point number.
3032 uintbe -- an unsigned big-endian whole byte integer.
3033 intbe -- a signed big-endian whole byte integer.
3034 floatbe - a big-endian floating point number.
3035 uintle -- an unsigned little-endian whole byte integer.
3036 intle -- a signed little-endian whole byte integer.
3037 floatle -- a little-endian floating point number.
3038 uintne -- an unsigned native-endian whole byte integer.
3039 intne -- a signed native-endian whole byte integer.
3040 floatne -- a native-endian floating point number.
3041 se -- a signed exponential-Golomb code.
3042 ue -- an unsigned exponential-Golomb code.
3043 sie -- a signed interleaved exponential-Golomb code.
3044 uie -- an unsigned interleaved exponential-Golomb code.
3045 bool -- a boolean (True or False).
3046 filename -- a file which will be opened in binary read-only mode.
3048 Other keyword arguments:
3049 length -- length of the bitstring in bits, if needed and appropriate.
3050 It must be supplied for all integer and float initialisers.
3051 offset -- bit offset to the data. These offset bits are
3052 ignored and this is intended for use when
3053 initialising using 'bytes' or 'filename'.
3057 if not isinstance(self.
_datastore, ByteStore):
3060 def __new__(cls, auto=None, length=None, offset=None, **kwargs):
3061 x = super(BitArray, cls).__new__(cls)
3062 y = Bits.__new__(BitArray, auto, length, offset, **kwargs)
3063 x._datastore = y._datastore
3067 """Append bs to current bitstring. Return self.
3069 bs -- the bitstring to append.
3076 """Return a new copy of the BitArray."""
3078 if not isinstance(self.
_datastore, ByteStore):
3083 s_copy._datastore = copy.copy(self.
_datastore)
3087 """Set item or range to new value.
3089 Indices are in units of the step parameter (default 1 bit).
3090 Stepping is used to specify the number of bits in each item.
3092 If the length of the bitstring is changed then pos will be moved
3093 to after the inserted section, otherwise it will remain unchanged.
3095 >>> s = BitArray('0xff')
3096 >>> s[0:1:4] = '0xe'
3107 if key.step
is not None:
3109 except AttributeError:
3113 if not 0 <= key < self.
len:
3114 raise IndexError(
"Slice index out of range.")
3115 if isinstance(value, numbers.Integral):
3119 if value
in (1, -1):
3122 raise ValueError(
"Cannot set a single bit with integer {0}.".format(value))
3140 temp.__setitem__(key, v)
3146 if not isinstance(value, numbers.Integral):
3151 raise TypeError(
"Bitstring, integer or string expected. "
3152 "Got {0}.".format(type(value)))
3153 if key.start
is not None:
3160 if key.stop
is not None:
3168 if isinstance(value, numbers.Integral):
3170 value = self.__class__(uint=value, length=stop - start)
3172 value = self.__class__(int=value, length=stop - start)
3173 stop = min(stop, self.
len)
3174 start = max(start, 0)
3175 start = min(start, stop)
3176 if (stop - start) == value.len:
3186 self.
_delete(stop - start, start)
3190 self.
_insert(value.__getitem__(
slice(
None,
None, 1)), start)
3195 """Delete item or range.
3197 Indices are in units of the step parameter (default 1 bit).
3198 Stepping is used to specify the number of bits in each item.
3200 >>> a = BitArray('0x001122')
3209 step = key.step
if key.step
is not None else 1
3210 except AttributeError:
3214 if not 0 <= key < self.
len:
3215 raise IndexError(
"Slice index out of range.")
3223 temp.__delitem__(key)
3227 if key.start
is not None:
3229 if key.start < 0
and stop
is None:
3237 stop = min(stop, self.
len)
3238 start = max(start, 0)
3239 start = min(start, stop)
3240 self.
_delete(stop - start, start)
3244 """Shift bits by n to the left in place. Return self.
3246 n -- the number of bits to shift. Must be >= 0.
3250 raise ValueError(
"Cannot shift by a negative amount.")
3252 raise ValueError(
"Cannot shift an empty bitstring.")
3255 n = min(n, self.
len)
3259 """Shift bits by n to the right in place. Return self.
3261 n -- the number of bits to shift. Must be >= 0.
3265 raise ValueError(
"Cannot shift by a negative amount.")
3267 raise ValueError(
"Cannot shift an empty bitstring.")
3270 n = min(n, self.
len)
3274 """Concatenate n copies of self in place. Return self.
3276 Called for expressions of the form 'a *= 3'.
3277 n -- The number of concatenations. Must be >= 0.
3281 raise ValueError(
"Cannot multiply by a negative integer.")
3282 return self.
_imul(n)
3284 def __ior__(self, bs):
3286 if self.
len != bs.len:
3287 raise ValueError(
"Bitstrings must have the same length "
3289 return self.
_ior(bs)
3291 def __iand__(self, bs):
3293 if self.
len != bs.len:
3294 raise ValueError(
"Bitstrings must have the same length "
3296 return self.
_iand(bs)
3298 def __ixor__(self, bs):
3300 if self.
len != bs.len:
3301 raise ValueError(
"Bitstrings must have the same length "
3303 return self.
_ixor(bs)
3305 def replace(self, old, new, start=None, end=None, count=None,
3307 """Replace all occurrences of old with new in place.
3309 Returns number of replacements made.
3311 old -- The bitstring to replace.
3312 new -- The replacement bitstring.
3313 start -- Any occurrences that start before this will not be replaced.
3315 end -- Any occurrences that finish after this will not be replaced.
3316 Defaults to self.len.
3317 count -- The maximum number of replacements to make. Defaults to
3318 replace all occurrences.
3319 bytealigned -- If True replacements will only be made on byte
3322 Raises ValueError if old is empty or if start or end are
3329 raise ValueError(
"Empty bitstring cannot be replaced.")
3331 if bytealigned
is None:
3332 bytealigned = globals()[
'bytealigned']
3334 if count
is not None:
3336 sections = self.
split(old, start, end, count, bytealigned)
3337 lengths = [s.len
for s
in sections]
3338 if len(lengths) == 1:
3343 new = copy.copy(self)
3344 positions = [lengths[0] + start]
3345 for l
in lengths[1:-1]:
3347 positions.append(positions[-1] + l)
3355 self[p:p + old.len] = new
3356 if old.len != new.len:
3357 diff = new.len - old.len
3361 if p + old.len <= newpos:
3366 except AttributeError:
3368 self[p:p + old.len] = new
3370 return len(lengths) - 1
3373 """Insert bs at bit position pos.
3375 bs -- The bitstring to insert.
3376 pos -- The bit position to insert at.
3378 Raises ValueError if pos < 0 or pos > self.len.
3389 except AttributeError:
3390 raise TypeError(
"insert require a bit position for this type.")
3393 if not 0 <= pos <= self.
len:
3394 raise ValueError(
"Invalid insert position.")
3398 """Overwrite with bs at bit position pos.
3400 bs -- The bitstring to overwrite with.
3401 pos -- The bit position to begin overwriting from.
3403 Raises ValueError if pos < 0 or pos + bs.len > self.len
3412 except AttributeError:
3413 raise TypeError(
"overwrite require a bit position for this type.")
3416 if pos < 0
or pos + bs.len > self.
len:
3417 raise ValueError(
"Overwrite exceeds boundary of bitstring.")
3420 self.
_pos = pos + bs.len
3421 except AttributeError:
3425 """Append a bitstring to the current bitstring.
3427 bs -- The bitstring to append.
3435 """Prepend a bitstring to the current bitstring.
3437 bs -- The bitstring to prepend.
3444 """Reverse bits in-place.
3446 start -- Position of first bit to reverse. Defaults to 0.
3447 end -- One past the position of the last bit to reverse.
3448 Defaults to self.len.
3450 Using on an empty bitstring will have no effect.
3452 Raises ValueError if start < 0, end > self.len or end < start.
3456 if start == 0
and end == self.
len:
3459 s = self.
_slice(start, end)
3463 def set(self, value, pos=None):
3464 """Set one or many bits to 1 or 0.
3466 value -- If True bits are set to 1, otherwise they are set to 0.
3467 pos -- Either a single bit position or an iterable of bit positions.
3468 Negative numbers are treated in the same way as slice indices.
3469 Defaults to the entire bitstring.
3471 Raises IndexError if pos < -self.len or pos >= self.len.
3476 pos = xrange(self.
len)
3482 if not 0 <= p < length:
3483 raise IndexError(
"Bit position {0} out of range.".format(p))
3489 if not 0 <= pos < length:
3490 raise IndexError(
"Bit position {0} out of range.".format(pos))
3494 """Invert one or many bits from 0 to 1 or vice versa.
3496 pos -- Either a single bit position or an iterable of bit positions.
3497 Negative numbers are treated in the same way as slice indices.
3499 Raises IndexError if pos < -self.len or pos >= self.len.
3505 if not isinstance(pos, collections.Iterable):
3512 if not 0 <= p < length:
3513 raise IndexError(
"Bit position {0} out of range.".format(p))
3516 def ror(self, bits, start=None, end=None):
3517 """Rotate bits to the right in-place.
3519 bits -- The number of bits to rotate by.
3520 start -- Start of slice to rotate. Defaults to 0.
3521 end -- End of slice to rotate. Defaults to self.len.
3523 Raises ValueError if bits < 0.
3527 raise Error(
"Cannot rotate an empty bitstring.")
3529 raise ValueError(
"Cannot rotate right by negative amount.")
3531 bits %= (end - start)
3534 rhs = self.
_slice(end - bits, end)
3535 self.
_delete(bits, end - bits)
3538 def rol(self, bits, start=None, end=None):
3539 """Rotate bits to the left in-place.
3541 bits -- The number of bits to rotate by.
3542 start -- Start of slice to rotate. Defaults to 0.
3543 end -- End of slice to rotate. Defaults to self.len.
3545 Raises ValueError if bits < 0.
3549 raise Error(
"Cannot rotate an empty bitstring.")
3551 raise ValueError(
"Cannot rotate left by negative amount.")
3553 bits %= (end - start)
3556 lhs = self.
_slice(start, start + bits)
3560 def byteswap(self, fmt=None, start=None, end=None, repeat=True):
3561 """Change the endianness in-place. Return number of repeats of fmt done.
3563 fmt -- A compact structure string, an integer number of bytes or
3564 an iterable of integers. Defaults to 0, which byte reverses the
3566 start -- Start bit position, defaults to 0.
3567 end -- End bit position, defaults to self.len.
3568 repeat -- If True (the default) the byte swapping pattern is repeated
3569 as much as possible.
3573 if fmt
is None or fmt == 0:
3575 bytesizes = [(end - start) // 8]
3576 elif isinstance(fmt, numbers.Integral):
3578 raise ValueError(
"Improper byte length {0}.".format(fmt))
3580 elif isinstance(fmt, basestring):
3581 m = STRUCT_PACK_RE.match(fmt)
3583 raise ValueError(
"Cannot parse format string {0}.".format(fmt))
3585 formatlist = re.findall(STRUCT_SPLIT_RE, m.group(
'fmt'))
3588 for f
in formatlist:
3590 bytesizes.append(PACK_CODE_SIZE[f])
3592 bytesizes.extend([PACK_CODE_SIZE[f[-1]]] * int(f[:-1]))
3593 elif isinstance(fmt, collections.Iterable):
3595 for bytesize
in bytesizes:
3596 if not isinstance(bytesize, numbers.Integral)
or bytesize < 0:
3597 raise ValueError(
"Improper byte length {0}.".format(bytesize))
3599 raise TypeError(
"Format must be an integer, string or iterable.")
3602 totalbitsize = 8 * sum(bytesizes)
3603 if not totalbitsize:
3610 finalbit = start + totalbitsize
3611 for patternend
in xrange(start + totalbitsize, finalbit + 1, totalbitsize):
3612 bytestart = patternend - totalbitsize
3613 for bytesize
in bytesizes:
3614 byteend = bytestart + bytesize * 8
3616 bytestart += bytesize * 8
3621 """Remove all bits, reset to zero length."""
3625 """Return a copy of the bitstring."""
3628 int = property(Bits._getint, Bits._setint,
3629 doc=
"""The bitstring as a two's complement signed int. Read and write.
3631 uint = property(Bits._getuint, Bits._setuint,
3632 doc=
"""The bitstring as a two's complement unsigned int. Read and write.
3634 float = property(Bits._getfloat, Bits._setfloat,
3635 doc=
"""The bitstring as a floating point number. Read and write.
3637 intbe = property(Bits._getintbe, Bits._setintbe,
3638 doc=
"""The bitstring as a two's complement big-endian signed int. Read and write.
3640 uintbe = property(Bits._getuintbe, Bits._setuintbe,
3641 doc=
"""The bitstring as a two's complement big-endian unsigned int. Read and write.
3643 floatbe = property(Bits._getfloat, Bits._setfloat,
3644 doc=
"""The bitstring as a big-endian floating point number. Read and write.
3646 intle = property(Bits._getintle, Bits._setintle,
3647 doc=
"""The bitstring as a two's complement little-endian signed int. Read and write.
3649 uintle = property(Bits._getuintle, Bits._setuintle,
3650 doc=
"""The bitstring as a two's complement little-endian unsigned int. Read and write.
3652 floatle = property(Bits._getfloatle, Bits._setfloatle,
3653 doc=
"""The bitstring as a little-endian floating point number. Read and write.
3655 intne = property(Bits._getintne, Bits._setintne,
3656 doc=
"""The bitstring as a two's complement native-endian signed int. Read and write.
3658 uintne = property(Bits._getuintne, Bits._setuintne,
3659 doc=
"""The bitstring as a two's complement native-endian unsigned int. Read and write.
3661 floatne = property(Bits._getfloatne, Bits._setfloatne,
3662 doc=
"""The bitstring as a native-endian floating point number. Read and write.
3664 ue = property(Bits._getue, Bits._setue,
3665 doc=
"""The bitstring as an unsigned exponential-Golomb code. Read and write.
3667 se = property(Bits._getse, Bits._setse,
3668 doc=
"""The bitstring as a signed exponential-Golomb code. Read and write.
3670 uie = property(Bits._getuie, Bits._setuie,
3671 doc=
"""The bitstring as an unsigned interleaved exponential-Golomb code. Read and write.
3673 sie = property(Bits._getsie, Bits._setsie,
3674 doc=
"""The bitstring as a signed interleaved exponential-Golomb code. Read and write.
3676 hex = property(Bits._gethex, Bits._sethex,
3677 doc=
"""The bitstring as a hexadecimal string. Read and write.
3679 bin = property(Bits._getbin, Bits._setbin_safe,
3680 doc=
"""The bitstring as a binary string. Read and write.
3682 oct = property(Bits._getoct, Bits._setoct,
3683 doc=
"""The bitstring as an octal string. Read and write.
3685 bool = property(Bits._getbool, Bits._setbool,
3686 doc=
"""The bitstring as a bool (True or False). Read and write.
3688 bytes = property(Bits._getbytes, Bits._setbytes_safe,
3689 doc=
"""The bitstring as a ordinary string. Read and write.
3694 """A container or stream holding an immutable sequence of bits.
3696 For a mutable container use the BitStream class instead.
3698 Methods inherited from Bits:
3700 all() -- Check if all specified bits are set to 1 or 0.
3701 any() -- Check if any of specified bits are set to 1 or 0.
3702 count() -- Count the number of bits set to 1 or 0.
3703 cut() -- Create generator of constant sized chunks.
3704 endswith() -- Return whether the bitstring ends with a sub-string.
3705 find() -- Find a sub-bitstring in the current bitstring.
3706 findall() -- Find all occurrences of a sub-bitstring in the current bitstring.
3707 join() -- Join bitstrings together using current bitstring.
3708 rfind() -- Seek backwards to find a sub-bitstring.
3709 split() -- Create generator of chunks split by a delimiter.
3710 startswith() -- Return whether the bitstring starts with a sub-bitstring.
3711 tobytes() -- Return bitstring as bytes, padding if needed.
3712 tofile() -- Write bitstring to file, padding if needed.
3713 unpack() -- Interpret bits using format string.
3717 bytealign() -- Align to next byte boundary.
3718 peek() -- Peek at and interpret next bits as a single item.
3719 peeklist() -- Peek at and interpret next bits as a list of items.
3720 read() -- Read and interpret next bits as a single item.
3721 readlist() -- Read and interpret next bits as a list of items.
3725 Also available are the operators [], ==, !=, +, *, ~, <<, >>, &, |, ^.
3729 bin -- The bitstring as a binary string.
3730 bool -- For single bit bitstrings, interpret as True or False.
3731 bytepos -- The current byte position in the bitstring.
3732 bytes -- The bitstring as a bytes object.
3733 float -- Interpret as a floating point number.
3734 floatbe -- Interpret as a big-endian floating point number.
3735 floatle -- Interpret as a little-endian floating point number.
3736 floatne -- Interpret as a native-endian floating point number.
3737 hex -- The bitstring as a hexadecimal string.
3738 int -- Interpret as a two's complement signed integer.
3739 intbe -- Interpret as a big-endian signed integer.
3740 intle -- Interpret as a little-endian signed integer.
3741 intne -- Interpret as a native-endian signed integer.
3742 len -- Length of the bitstring in bits.
3743 oct -- The bitstring as an octal string.
3744 pos -- The current bit position in the bitstring.
3745 se -- Interpret as a signed exponential-Golomb code.
3746 ue -- Interpret as an unsigned exponential-Golomb code.
3747 sie -- Interpret as a signed interleaved exponential-Golomb code.
3748 uie -- Interpret as an unsigned interleaved exponential-Golomb code.
3749 uint -- Interpret as a two's complement unsigned integer.
3750 uintbe -- Interpret as a big-endian unsigned integer.
3751 uintle -- Interpret as a little-endian unsigned integer.
3752 uintne -- Interpret as a native-endian unsigned integer.
3756 __slots__ = (
'_pos')
3758 def __init__(self, auto=None, length=None, offset=None, **kwargs):
3759 """Either specify an 'auto' initialiser:
3760 auto -- a string of comma separated tokens, an integer, a file object,
3761 a bytearray, a boolean iterable or another bitstring.
3763 Or initialise via **kwargs with one (and only one) of:
3764 bytes -- raw data as a string, for example read from a binary file.
3765 bin -- binary string representation, e.g. '0b001010'.
3766 hex -- hexadecimal string representation, e.g. '0x2ef'
3767 oct -- octal string representation, e.g. '0o777'.
3768 uint -- an unsigned integer.
3769 int -- a signed integer.
3770 float -- a floating point number.
3771 uintbe -- an unsigned big-endian whole byte integer.
3772 intbe -- a signed big-endian whole byte integer.
3773 floatbe - a big-endian floating point number.
3774 uintle -- an unsigned little-endian whole byte integer.
3775 intle -- a signed little-endian whole byte integer.
3776 floatle -- a little-endian floating point number.
3777 uintne -- an unsigned native-endian whole byte integer.
3778 intne -- a signed native-endian whole byte integer.
3779 floatne -- a native-endian floating point number.
3780 se -- a signed exponential-Golomb code.
3781 ue -- an unsigned exponential-Golomb code.
3782 sie -- a signed interleaved exponential-Golomb code.
3783 uie -- an unsigned interleaved exponential-Golomb code.
3784 bool -- a boolean (True or False).
3785 filename -- a file which will be opened in binary read-only mode.
3787 Other keyword arguments:
3788 length -- length of the bitstring in bits, if needed and appropriate.
3789 It must be supplied for all integer and float initialisers.
3790 offset -- bit offset to the data. These offset bits are
3791 ignored and this is intended for use when
3792 initialising using 'bytes' or 'filename'.
3797 def __new__(cls, auto=None, length=None, offset=None, **kwargs):
3798 x = super(ConstBitStream, cls).__new__(cls)
3799 x._initialise(auto, length, offset, **kwargs)
3803 """Move to absolute byte-aligned position in stream."""
3807 """Return the current position in the stream in bytes. Must be byte aligned."""
3810 return self.
_pos // 8
3813 """Move to absolute postion bit in bitstream."""
3815 raise ValueError(
"Bit position cannot be negative.")
3817 raise ValueError(
"Cannot seek past the end of the data.")
3821 """Return the current position in the stream in bits."""
3829 """Return a new copy of the ConstBitStream for the copy module."""
3839 """Concatenate bitstrings and return new bitstring.
3841 bs -- the bitstring to append.
3844 s = Bits.__add__(self, bs)
3849 """Interpret next bits according to the format string and return result.
3851 fmt -- Token string describing how to interpret the next bits.
3853 Token examples: 'int:12' : 12 bits as a signed integer
3854 'uint:8' : 8 bits as an unsigned integer
3855 'float:64' : 8 bytes as a big-endian float
3856 'intbe:16' : 2 bytes as a big-endian signed integer
3857 'uintbe:16' : 2 bytes as a big-endian unsigned integer
3858 'intle:32' : 4 bytes as a little-endian signed integer
3859 'uintle:32' : 4 bytes as a little-endian unsigned integer
3860 'floatle:64': 8 bytes as a little-endian float
3861 'intne:24' : 3 bytes as a native-endian signed integer
3862 'uintne:24' : 3 bytes as a native-endian unsigned integer
3863 'floatne:32': 4 bytes as a native-endian float
3864 'hex:80' : 80 bits as a hex string
3865 'oct:9' : 9 bits as an octal string
3866 'bin:1' : single bit binary string
3867 'ue' : next bits as unsigned exp-Golomb code
3868 'se' : next bits as signed exp-Golomb code
3869 'uie' : next bits as unsigned interleaved exp-Golomb code
3870 'sie' : next bits as signed interleaved exp-Golomb code
3871 'bits:5' : 5 bits as a bitstring
3872 'bytes:10' : 10 bytes as a bytes object
3873 'bool' : 1 bit as a bool
3874 'pad:3' : 3 bits of padding to ignore - returns None
3876 fmt may also be an integer, which will be treated like the 'bits' token.
3878 The position in the bitstring is advanced to after the read items.
3880 Raises ReadError if not enough bits are available.
3881 Raises ValueError if the format is not understood.
3884 if isinstance(fmt, numbers.Integral):
3886 raise ValueError(
"Cannot read negative amount.")
3887 if fmt > self.
len - self.
_pos:
3888 raise ReadError(
"Cannot read {0} bits, only {1} available.",
3897 raise ValueError(
"Format string should be a single token, not {0} "
3898 "tokens - use readlist() instead.".format(len(token)))
3899 name, length, _ = token[0]
3906 """Interpret next bits according to format string(s) and return list.
3908 fmt -- A single string or list of strings with comma separated tokens
3909 describing how to interpret the next bits in the bitstring. Items
3910 can also be integers, for reading new bitstring of the given length.
3911 kwargs -- A dictionary or keyword-value pairs - the keywords used in the
3912 format string will be replaced with their given value.
3914 The position in the bitstring is advanced to after the read items.
3916 Raises ReadError is not enough bits are available.
3917 Raises ValueError if the format is not understood.
3919 See the docstring for 'read' for token examples. 'pad' tokens are skipped
3920 and not added to the returned list.
3922 >>> h, b1, b2 = s.readlist('hex:20, bin:5, bin:3')
3923 >>> i, bs1, bs2 = s.readlist(['uint:12', 10, 10])
3930 """Read up to and including next occurrence of bs and return result.
3932 bs -- The bitstring to find. An integer is not permitted.
3933 bytealigned -- If True the bitstring will only be
3934 found on byte boundaries.
3936 Raises ValueError if bs is empty.
3937 Raises ReadError if bs is not found.
3940 if isinstance(bs, numbers.Integral):
3941 raise ValueError(
"Integers cannot be searched for")
3944 p = self.
find(bs, self.
_pos, bytealigned=bytealigned)
3951 """Interpret next bits according to format string and return result.
3953 fmt -- Token string describing how to interpret the next bits.
3955 The position in the bitstring is not changed. If not enough bits are
3956 available then all bits to the end of the bitstring will be used.
3958 Raises ReadError if not enough bits are available.
3959 Raises ValueError if the format is not understood.
3961 See the docstring for 'read' for token examples.
3964 pos_before = self.
_pos
3965 value = self.
read(fmt)
3966 self.
_pos = pos_before
3970 """Interpret next bits according to format string(s) and return list.
3972 fmt -- One or more strings with comma separated tokens describing
3973 how to interpret the next bits in the bitstring.
3974 kwargs -- A dictionary or keyword-value pairs - the keywords used in the
3975 format string will be replaced with their given value.
3977 The position in the bitstring is not changed. If not enough bits are
3978 available then all bits to the end of the bitstring will be used.
3980 Raises ReadError if not enough bits are available.
3981 Raises ValueError if the format is not understood.
3983 See the docstring for 'read' for token examples.
3987 return_values = self.
readlist(fmt, **kwargs)
3989 return return_values
3992 """Align to next byte and return number of skipped bits.
3994 Raises ValueError if the end of the bitstring is reached before
3995 aligning to the next byte.
3998 skipped = (8 - (self.
_pos % 8)) % 8
4003 pos = property(_getbitpos, _setbitpos,
4004 doc=
"""The position in the bitstring in bits. Read and write.
4006 bitpos = property(_getbitpos, _setbitpos,
4007 doc=
"""The position in the bitstring in bits. Read and write.
4009 bytepos = property(_getbytepos, _setbytepos,
4010 doc=
"""The position in the bitstring in bytes. Read and write.
4015 """A container or stream holding a mutable sequence of bits
4017 Subclass of the ConstBitStream and BitArray classes. Inherits all of
4022 all() -- Check if all specified bits are set to 1 or 0.
4023 any() -- Check if any of specified bits are set to 1 or 0.
4024 append() -- Append a bitstring.
4025 bytealign() -- Align to next byte boundary.
4026 byteswap() -- Change byte endianness in-place.
4027 count() -- Count the number of bits set to 1 or 0.
4028 cut() -- Create generator of constant sized chunks.
4029 endswith() -- Return whether the bitstring ends with a sub-string.
4030 find() -- Find a sub-bitstring in the current bitstring.
4031 findall() -- Find all occurrences of a sub-bitstring in the current bitstring.
4032 insert() -- Insert a bitstring.
4033 invert() -- Flip bit(s) between one and zero.
4034 join() -- Join bitstrings together using current bitstring.
4035 overwrite() -- Overwrite a section with a new bitstring.
4036 peek() -- Peek at and interpret next bits as a single item.
4037 peeklist() -- Peek at and interpret next bits as a list of items.
4038 prepend() -- Prepend a bitstring.
4039 read() -- Read and interpret next bits as a single item.
4040 readlist() -- Read and interpret next bits as a list of items.
4041 replace() -- Replace occurrences of one bitstring with another.
4042 reverse() -- Reverse bits in-place.
4043 rfind() -- Seek backwards to find a sub-bitstring.
4044 rol() -- Rotate bits to the left.
4045 ror() -- Rotate bits to the right.
4046 set() -- Set bit(s) to 1 or 0.
4047 split() -- Create generator of chunks split by a delimiter.
4048 startswith() -- Return whether the bitstring starts with a sub-bitstring.
4049 tobytes() -- Return bitstring as bytes, padding if needed.
4050 tofile() -- Write bitstring to file, padding if needed.
4051 unpack() -- Interpret bits using format string.
4055 Mutating operators are available: [], <<=, >>=, +=, *=, &=, |= and ^=
4056 in addition to [], ==, !=, +, *, ~, <<, >>, &, | and ^.
4060 bin -- The bitstring as a binary string.
4061 bool -- For single bit bitstrings, interpret as True or False.
4062 bytepos -- The current byte position in the bitstring.
4063 bytes -- The bitstring as a bytes object.
4064 float -- Interpret as a floating point number.
4065 floatbe -- Interpret as a big-endian floating point number.
4066 floatle -- Interpret as a little-endian floating point number.
4067 floatne -- Interpret as a native-endian floating point number.
4068 hex -- The bitstring as a hexadecimal string.
4069 int -- Interpret as a two's complement signed integer.
4070 intbe -- Interpret as a big-endian signed integer.
4071 intle -- Interpret as a little-endian signed integer.
4072 intne -- Interpret as a native-endian signed integer.
4073 len -- Length of the bitstring in bits.
4074 oct -- The bitstring as an octal string.
4075 pos -- The current bit position in the bitstring.
4076 se -- Interpret as a signed exponential-Golomb code.
4077 ue -- Interpret as an unsigned exponential-Golomb code.
4078 sie -- Interpret as a signed interleaved exponential-Golomb code.
4079 uie -- Interpret as an unsigned interleaved exponential-Golomb code.
4080 uint -- Interpret as a two's complement unsigned integer.
4081 uintbe -- Interpret as a big-endian unsigned integer.
4082 uintle -- Interpret as a little-endian unsigned integer.
4083 uintne -- Interpret as a native-endian unsigned integer.
4092 def __init__(self, auto=None, length=None, offset=None, **kwargs):
4093 """Either specify an 'auto' initialiser:
4094 auto -- a string of comma separated tokens, an integer, a file object,
4095 a bytearray, a boolean iterable or another bitstring.
4097 Or initialise via **kwargs with one (and only one) of:
4098 bytes -- raw data as a string, for example read from a binary file.
4099 bin -- binary string representation, e.g. '0b001010'.
4100 hex -- hexadecimal string representation, e.g. '0x2ef'
4101 oct -- octal string representation, e.g. '0o777'.
4102 uint -- an unsigned integer.
4103 int -- a signed integer.
4104 float -- a floating point number.
4105 uintbe -- an unsigned big-endian whole byte integer.
4106 intbe -- a signed big-endian whole byte integer.
4107 floatbe - a big-endian floating point number.
4108 uintle -- an unsigned little-endian whole byte integer.
4109 intle -- a signed little-endian whole byte integer.
4110 floatle -- a little-endian floating point number.
4111 uintne -- an unsigned native-endian whole byte integer.
4112 intne -- a signed native-endian whole byte integer.
4113 floatne -- a native-endian floating point number.
4114 se -- a signed exponential-Golomb code.
4115 ue -- an unsigned exponential-Golomb code.
4116 sie -- a signed interleaved exponential-Golomb code.
4117 uie -- an unsigned interleaved exponential-Golomb code.
4118 bool -- a boolean (True or False).
4119 filename -- a file which will be opened in binary read-only mode.
4121 Other keyword arguments:
4122 length -- length of the bitstring in bits, if needed and appropriate.
4123 It must be supplied for all integer and float initialisers.
4124 offset -- bit offset to the data. These offset bits are
4125 ignored and this is intended for use when
4126 initialising using 'bytes' or 'filename'.
4131 if not isinstance(self.
_datastore, ByteStore):
4134 def __new__(cls, auto=None, length=None, offset=None, **kwargs):
4135 x = super(BitStream, cls).__new__(cls)
4136 x._initialise(auto, length, offset, **kwargs)
4140 """Return a new copy of the BitStream."""
4143 if not isinstance(self.
_datastore, ByteStore):
4154 """Prepend a bitstring to the current bitstring.
4156 bs -- The bitstring to prepend.
4165 """Pack the values according to the format string and return a new BitStream.
4167 fmt -- A single string or a list of strings with comma separated tokens
4168 describing how to create the BitStream.
4169 values -- Zero or more values to pack according to the format.
4170 kwargs -- A dictionary or keyword-value pairs - the keywords used in the
4171 format string will be replaced with their given value.
4173 Token examples: 'int:12' : 12 bits as a signed integer
4174 'uint:8' : 8 bits as an unsigned integer
4175 'float:64' : 8 bytes as a big-endian float
4176 'intbe:16' : 2 bytes as a big-endian signed integer
4177 'uintbe:16' : 2 bytes as a big-endian unsigned integer
4178 'intle:32' : 4 bytes as a little-endian signed integer
4179 'uintle:32' : 4 bytes as a little-endian unsigned integer
4180 'floatle:64': 8 bytes as a little-endian float
4181 'intne:24' : 3 bytes as a native-endian signed integer
4182 'uintne:24' : 3 bytes as a native-endian unsigned integer
4183 'floatne:32': 4 bytes as a native-endian float
4184 'hex:80' : 80 bits as a hex string
4185 'oct:9' : 9 bits as an octal string
4186 'bin:1' : single bit binary string
4187 'ue' / 'uie': next bits as unsigned exp-Golomb code
4188 'se' / 'sie': next bits as signed exp-Golomb code
4189 'bits:5' : 5 bits as a bitstring object
4190 'bytes:10' : 10 bytes as a bytes object
4191 'bool' : 1 bit as a bool
4192 'pad:3' : 3 zero bits as padding
4194 >>> s = pack('uint:12, bits', 100, '0xffe')
4195 >>> t = pack(['bits', 'bin:3'], s, '111')
4196 >>> u = pack('uint:8=a, uint:8=b, uint:55=a', a=6, b=44)
4200 if isinstance(fmt, basestring):
4204 _, tkns =
tokenparser(f_item, tuple(sorted(kwargs.keys())))
4206 except ValueError
as e:
4208 value_iter = iter(values)
4211 for name, length, value
in tokens:
4214 value = kwargs[value]
4216 if length
in kwargs:
4217 length = kwargs[length]
4219 if name
in kwargs
and length
is None and value
is None:
4220 s.append(kwargs[name])
4222 if length
is not None:
4223 length = int(length)
4224 if value
is None and name !=
'pad':
4226 value = next(value_iter)
4227 s._append(BitStream._init_with_token(name, length, value))
4228 except StopIteration:
4229 raise CreationError(
"Not enough parameters present to pack according to the "
4230 "format. {0} values are needed.", len(tokens))
4233 except StopIteration:
4236 raise CreationError(
"Too many parameters present to pack according to the format.")
4240 ConstBitArray = Bits
4241 BitString = BitStream
4243 __all__ = [
'ConstBitArray',
'ConstBitStream',
'BitStream',
'BitArray',
4244 'Bits',
'BitString',
'pack',
'Error',
'ReadError',
4245 'InterpretError',
'ByteAlignError',
'CreationError',
'bytealigned']