Belle II Software development
ConstBitStream Class Reference
Inheritance diagram for ConstBitStream:
Bits BitStream

Public Member Functions

 __init__ (self, auto=None, length=None, offset=None, **kwargs)
 
 __new__ (cls, auto=None, length=None, offset=None, **kwargs)
 
 __copy__ (self)
 
 __add__ (self, bs)
 
 read (self, fmt)
 
 readlist (self, fmt, **kwargs)
 
 readto (self, bs, bytealigned=None)
 
 peek (self, fmt)
 
 peeklist (self, fmt, **kwargs)
 
 bytealign (self)
 
 __lt__ (self, other)
 
 __gt__ (self, other)
 
 __le__ (self, other)
 
 __ge__ (self, other)
 
 __radd__ (self, bs)
 
 __getitem__ (self, key)
 
 __len__ (self)
 
 __str__ (self)
 
 __repr__ (self)
 
 __eq__ (self, bs)
 
 __ne__ (self, bs)
 
 __invert__ (self)
 
 __lshift__ (self, n)
 
 __rshift__ (self, n)
 
 __mul__ (self, n)
 
 __rmul__ (self, n)
 
 __and__ (self, bs)
 
 __rand__ (self, bs)
 
 __or__ (self, bs)
 
 __ror__ (self, bs)
 
 __xor__ (self, bs)
 
 __rxor__ (self, bs)
 
 __contains__ (self, bs)
 
 __hash__ (self)
 
 __nonzero__ (self)
 
 unpack (self, fmt, **kwargs)
 
 find (self, bs, start=None, end=None, bytealigned=None)
 
 findall (self, bs, start=None, end=None, count=None, bytealigned=None)
 
 rfind (self, bs, start=None, end=None, bytealigned=None)
 
 cut (self, bits, start=None, end=None, count=None)
 
 split (self, delimiter, start=None, end=None, count=None, bytealigned=None)
 
 join (self, sequence)
 
 tobytes (self)
 
 tofile (self, f)
 
 startswith (self, prefix, start=None, end=None)
 
 endswith (self, suffix, start=None, end=None)
 
 all (self, value, pos=None)
 
 any (self, value, pos=None)
 
 count (self, value)
 

Protected Member Functions

 _setbytepos (self, bytepos)
 
 _getbytepos (self)
 
 _setbitpos (self, pos)
 
 _getbitpos (self)
 
 _clear (self)
 
 _initialise (self, auto, length, offset, **kwargs)
 
 _initialise_from_auto (self, auto, length, offset)
 
 _assertsanity (self)
 
 _init_with_token (cls, name, token_length, value)
 
 _setauto (self, s, length, offset)
 
 _setfile (self, filename, length, offset)
 
 _setbytes_safe (self, data, length=None, offset=0)
 
 _setbytes_unsafe (self, data, length, offset)
 
 _readbytes (self, length, start)
 
 _getbytes (self)
 
 _setuint (self, uint, length=None)
 
 _readuint (self, length, start)
 
 _getuint (self)
 
 _setint (self, int_, length=None)
 
 _readint (self, length, start)
 
 _getint (self)
 
 _setuintbe (self, uintbe, length=None)
 
 _readuintbe (self, length, start)
 
 _getuintbe (self)
 
 _setintbe (self, intbe, length=None)
 
 _readintbe (self, length, start)
 
 _getintbe (self)
 
 _setuintle (self, uintle, length=None)
 
 _readuintle (self, length, start)
 
 _getuintle (self)
 
 _setintle (self, intle, length=None)
 
 _readintle (self, length, start)
 
 _getintle (self)
 
 _setfloat (self, f, length=None)
 
 _readfloat (self, length, start)
 
 _getfloat (self)
 
 _setfloatle (self, f, length=None)
 
 _readfloatle (self, length, start)
 
 _getfloatle (self)
 
 _setue (self, i)
 
 _readue (self, pos)
 
 _getue (self)
 
 _setse (self, i)
 
 _getse (self)
 
 _readse (self, pos)
 
 _setuie (self, i)
 
 _readuie (self, pos)
 
 _getuie (self)
 
 _setsie (self, i)
 
 _getsie (self)
 
 _readsie (self, pos)
 
 _setbool (self, value)
 
 _getbool (self)
 
 _readbool (self, pos)
 
 _setbin_safe (self, binstring)
 
 _setbin_unsafe (self, binstring)
 
 _readbin (self, length, start)
 
 _getbin (self)
 
 _setoct (self, octstring)
 
 _readoct (self, length, start)
 
 _getoct (self)
 
 _sethex (self, hexstring)
 
 _readhex (self, length, start)
 
 _gethex (self)
 
 _getoffset (self)
 
 _getlength (self)
 
 _ensureinmemory (self)
 
 _converttobitstring (cls, bs, offset=0, cache=None)
 
 _copy (self)
 
 _slice (self, start, end)
 
 _readtoken (self, name, pos, length)
 
 _append (self, bs)
 
 _prepend (self, bs)
 
 _reverse (self)
 
 _truncatestart (self, bits)
 
 _truncateend (self, bits)
 
 _insert (self, bs, pos)
 
 _overwrite (self, bs, pos)
 
 _delete (self, bits, pos)
 
 _reversebytes (self, start, end)
 
 _set (self, pos)
 
 _unset (self, pos)
 
 _invert (self, pos)
 
 _invert_all (self)
 
 _ilshift (self, n)
 
 _irshift (self, n)
 
 _imul (self, n)
 
 _inplace_logical_helper (self, bs, f)
 
 _ior (self, bs)
 
 _iand (self, bs)
 
 _ixor (self, bs)
 
 _readbits (self, length, start)
 
 _validate_slice (self, start, end)
 
 _readlist (self, fmt, pos, **kwargs)
 
 _findbytes (self, bytes_, start, end, bytealigned)
 
 _findregex (self, reg_ex, start, end, bytealigned)
 

Protected Attributes

 _datastore
 
 _pos = pos
 

Static Protected Attributes

 _setfloatne = _setfloatle
 
 _readfloatne = _readfloatle
 
 _getfloatne = _getfloatle
 
 _setuintne = _setuintle
 
 _readuintne = _readuintle
 
 _getuintne = _getuintle
 
 _setintne = _setintle
 
 _readintne = _readintle
 
 _getintne = _getintle
 

Properties

 pos
 
 bitpos
 
 bytepos
 
 _offset = property(_getoffset)
 
 len
 
 length
 
 bool
 
 hex
 
 bin
 
 oct
 
 bytes
 
 int
 
 uint
 
 float
 
 intbe
 
 uintbe
 
 floatbe
 
 intle
 
 uintle
 
 floatle
 
 intne
 
 uintne
 
 floatne
 
 ue
 
 se
 
 uie
 
 sie
 

Static Private Attributes

tuple __slots__ = ('_pos')
 
 __bool__ = __nonzero__
 

Detailed Description

A container or stream holding an immutable sequence of bits.

For a mutable container use the BitStream class instead.

Methods inherited from Bits:

all() -- Check if all specified bits are set to 1 or 0.
any() -- Check if any of specified bits are set to 1 or 0.
count() -- Count the number of bits set to 1 or 0.
cut() -- Create generator of constant sized chunks.
endswith() -- Return whether the bitstring ends with a sub-string.
find() -- Find a sub-bitstring in the current bitstring.
findall() -- Find all occurrences of a sub-bitstring in the current bitstring.
join() -- Join bitstrings together using current bitstring.
rfind() -- Seek backwards to find a sub-bitstring.
split() -- Create generator of chunks split by a delimiter.
startswith() -- Return whether the bitstring starts with a sub-bitstring.
tobytes() -- Return bitstring as bytes, padding if needed.
tofile() -- Write bitstring to file, padding if needed.
unpack() -- Interpret bits using format string.

Other methods:

bytealign() -- Align to next byte boundary.
peek() -- Peek at and interpret next bits as a single item.
peeklist() -- Peek at and interpret next bits as a list of items.
read() -- Read and interpret next bits as a single item.
readlist() -- Read and interpret next bits as a list of items.

Special methods:

Also available are the operators [], ==, !=, +, *, ~, <<, >>, &, |, ^.

Properties:

bin -- The bitstring as a binary string.
bool -- For single bit bitstrings, interpret as True or False.
bytepos -- The current byte position in the bitstring.
bytes -- The bitstring as a bytes object.
float -- Interpret as a floating point number.
floatbe -- Interpret as a big-endian floating point number.
floatle -- Interpret as a little-endian floating point number.
floatne -- Interpret as a native-endian floating point number.
hex -- The bitstring as a hexadecimal string.
int -- Interpret as a two's complement signed integer.
intbe -- Interpret as a big-endian signed integer.
intle -- Interpret as a little-endian signed integer.
intne -- Interpret as a native-endian signed integer.
len -- Length of the bitstring in bits.
oct -- The bitstring as an octal string.
pos -- The current bit position in the bitstring.
se -- Interpret as a signed exponential-Golomb code.
ue -- Interpret as an unsigned exponential-Golomb code.
sie -- Interpret as a signed interleaved exponential-Golomb code.
uie -- Interpret as an unsigned interleaved exponential-Golomb code.
uint -- Interpret as a two's complement unsigned integer.
uintbe -- Interpret as a big-endian unsigned integer.
uintle -- Interpret as a little-endian unsigned integer.
uintne -- Interpret as a native-endian unsigned integer.

Definition at line 3699 of file bitstring.py.

Constructor & Destructor Documentation

◆ __init__()

__init__ ( self,
auto = None,
length = None,
offset = None,
** kwargs )
Either specify an 'auto' initialiser:
auto -- a string of comma separated tokens, an integer, a file object,
        a bytearray, a boolean iterable or another bitstring.

Or initialise via **kwargs with one (and only one) of:
bytes -- raw data as a string, for example read from a binary file.
bin -- binary string representation, e.g. '0b001010'.
hex -- hexadecimal string representation, e.g. '0x2ef'
oct -- octal string representation, e.g. '0o777'.
uint -- an unsigned integer.
int -- a signed integer.
float -- a floating point number.
uintbe -- an unsigned big-endian whole byte integer.
intbe -- a signed big-endian whole byte integer.
floatbe - a big-endian floating point number.
uintle -- an unsigned little-endian whole byte integer.
intle -- a signed little-endian whole byte integer.
floatle -- a little-endian floating point number.
uintne -- an unsigned native-endian whole byte integer.
intne -- a signed native-endian whole byte integer.
floatne -- a native-endian floating point number.
se -- a signed exponential-Golomb code.
ue -- an unsigned exponential-Golomb code.
sie -- a signed interleaved exponential-Golomb code.
uie -- an unsigned interleaved exponential-Golomb code.
bool -- a boolean (True or False).
filename -- a file which will be opened in binary read-only mode.

Other keyword arguments:
length -- length of the bitstring in bits, if needed and appropriate.
          It must be supplied for all integer and float initialisers.
offset -- bit offset to the data. These offset bits are
          ignored and this is intended for use when
          initialising using 'bytes' or 'filename'.

Definition at line 3764 of file bitstring.py.

3764 def __init__(self, auto=None, length=None, offset=None, **kwargs):
3765 """Either specify an 'auto' initialiser:
3766 auto -- a string of comma separated tokens, an integer, a file object,
3767 a bytearray, a boolean iterable or another bitstring.
3768
3769 Or initialise via **kwargs with one (and only one) of:
3770 bytes -- raw data as a string, for example read from a binary file.
3771 bin -- binary string representation, e.g. '0b001010'.
3772 hex -- hexadecimal string representation, e.g. '0x2ef'
3773 oct -- octal string representation, e.g. '0o777'.
3774 uint -- an unsigned integer.
3775 int -- a signed integer.
3776 float -- a floating point number.
3777 uintbe -- an unsigned big-endian whole byte integer.
3778 intbe -- a signed big-endian whole byte integer.
3779 floatbe - a big-endian floating point number.
3780 uintle -- an unsigned little-endian whole byte integer.
3781 intle -- a signed little-endian whole byte integer.
3782 floatle -- a little-endian floating point number.
3783 uintne -- an unsigned native-endian whole byte integer.
3784 intne -- a signed native-endian whole byte integer.
3785 floatne -- a native-endian floating point number.
3786 se -- a signed exponential-Golomb code.
3787 ue -- an unsigned exponential-Golomb code.
3788 sie -- a signed interleaved exponential-Golomb code.
3789 uie -- an unsigned interleaved exponential-Golomb code.
3790 bool -- a boolean (True or False).
3791 filename -- a file which will be opened in binary read-only mode.
3792
3793 Other keyword arguments:
3794 length -- length of the bitstring in bits, if needed and appropriate.
3795 It must be supplied for all integer and float initialisers.
3796 offset -- bit offset to the data. These offset bits are
3797 ignored and this is intended for use when
3798 initialising using 'bytes' or 'filename'.
3799
3800 """
3801 self._pos = 0
3802

Member Function Documentation

◆ __add__()

__add__ ( self,
bs )
Concatenate bitstrings and return new bitstring.

bs -- the bitstring to append.

Definition at line 3844 of file bitstring.py.

3844 def __add__(self, bs):
3845 """Concatenate bitstrings and return new bitstring.
3846
3847 bs -- the bitstring to append.
3848
3849 """
3850 s = Bits.__add__(self, bs)
3851 s._pos = 0
3852 return s
3853

◆ __and__()

__and__ ( self,
bs )
inherited
Bit-wise 'and' between two bitstrings. Returns new bitstring.

bs -- The bitstring to '&' with.

Raises ValueError if the two bitstrings have differing lengths.

Definition at line 1079 of file bitstring.py.

1079 def __and__(self, bs):
1080 """Bit-wise 'and' between two bitstrings. Returns new bitstring.
1081
1082 bs -- The bitstring to '&' with.
1083
1084 Raises ValueError if the two bitstrings have differing lengths.
1085
1086 """
1087 bs = Bits(bs)
1088 if self.len != bs.len:
1089 raise ValueError("Bitstrings must have the same length "
1090 "for & operator.")
1091 s = self._copy()
1092 s._iand(bs)
1093 return s
1094

◆ __contains__()

__contains__ ( self,
bs )
inherited
Return whether bs is contained in the current bitstring.

bs -- The bitstring to search for.

Definition at line 1157 of file bitstring.py.

1157 def __contains__(self, bs):
1158 """Return whether bs is contained in the current bitstring.
1159
1160 bs -- The bitstring to search for.
1161
1162 """
1163 # Don't want to change pos
1164 try:
1165 pos = self._pos
1166 except AttributeError:
1167 pass
1168 found = Bits.find(self, bs, bytealigned=False)
1169 try:
1170 self._pos = pos
1171 except AttributeError:
1172 pass
1173 return bool(found)
1174

◆ __copy__()

__copy__ ( self)
Return a new copy of the ConstBitStream for the copy module.

Definition at line 3834 of file bitstring.py.

3834 def __copy__(self):
3835 """Return a new copy of the ConstBitStream for the copy module."""
3836 # Note that if you want a new copy (different ID), use _copy instead.
3837 # The copy can use the same datastore as it's immutable.
3838 s = ConstBitStream()
3839 s._datastore = self._datastore
3840 # Reset the bit position, don't copy it.
3841 s._pos = 0
3842 return s
3843

◆ __eq__()

__eq__ ( self,
bs )
inherited
Return True if two bitstrings have the same binary representation.

>>> BitArray('0b1110') == '0xe'
True

Definition at line 990 of file bitstring.py.

990 def __eq__(self, bs):
991 """Return True if two bitstrings have the same binary representation.
992
993 >>> BitArray('0b1110') == '0xe'
994 True
995
996 """
997 try:
998 bs = Bits(bs)
999 except TypeError:
1000 return False
1001 return equal(self._datastore, bs._datastore)
1002

◆ __ge__()

__ge__ ( self,
other )
inherited

Definition at line 865 of file bitstring.py.

865 def __ge__(self, other):
866 raise TypeError("unorderable type: {0}".format(type(self).__name__))
867

◆ __getitem__()

__getitem__ ( self,
key )
inherited
Return a new bitstring representing a slice of the current bitstring.

Indices are in units of the step parameter (default 1 bit).
Stepping is used to specify the number of bits in each item.

>>> print BitArray('0b00110')[1:4]
'0b011'
>>> print BitArray('0x00112233')[1:3:8]
'0x1122'

Definition at line 893 of file bitstring.py.

893 def __getitem__(self, key):
894 """Return a new bitstring representing a slice of the current bitstring.
895
896 Indices are in units of the step parameter (default 1 bit).
897 Stepping is used to specify the number of bits in each item.
898
899 >>> print BitArray('0b00110')[1:4]
900 '0b011'
901 >>> print BitArray('0x00112233')[1:3:8]
902 '0x1122'
903
904 """
905 length = self.len
906 try:
907 step = key.step if key.step is not None else 1
908 except AttributeError:
909 # single element
910 if key < 0:
911 key += length
912 if not 0 <= key < length:
913 raise IndexError("Slice index out of range.")
914 # Single bit, return True or False
915 return self._datastore.getbit(key)
916 else:
917 if step != 1:
918 # convert to binary string and use string slicing
919 bs = self.__class__()
920 bs._setbin_unsafe(self._getbin().__getitem__(key))
921 return bs
922 start, stop = 0, length
923 if key.start is not None:
924 start = key.start
925 if key.start < 0:
926 start += stop
927 if key.stop is not None:
928 stop = key.stop
929 if key.stop < 0:
930 stop += length
931 start = max(start, 0)
932 stop = min(stop, length)
933 if start < stop:
934 return self._slice(start, stop)
935 else:
936 return self.__class__()
937

◆ __gt__()

__gt__ ( self,
other )
inherited

Definition at line 859 of file bitstring.py.

859 def __gt__(self, other):
860 raise TypeError("unorderable type: {0}".format(type(self).__name__))
861

◆ __hash__()

__hash__ ( self)
inherited
Return an integer hash of the object.

Definition at line 1175 of file bitstring.py.

1175 def __hash__(self):
1176 """Return an integer hash of the object."""
1177 # We can't in general hash the whole bitstring (it could take hours!)
1178 # So instead take some bits from the start and end.
1179 if self.len <= 160:
1180 # Use the whole bitstring.
1181 shorter = self
1182 else:
1183 # Take 10 bytes from start and end
1184 shorter = self[:80] + self[-80:]
1185 h = 0
1186 for byte in shorter.tobytes():
1187 try:
1188 h = (h << 4) + ord(byte)
1189 except TypeError:
1190 # Python 3
1191 h = (h << 4) + byte
1192 g = h & 0xf0000000
1193 if g & (1 << 31):
1194 h ^= (g >> 24)
1195 h ^= g
1196 return h % 1442968193
1197

◆ __invert__()

__invert__ ( self)
inherited
Return bitstring with every bit inverted.

Raises Error if the bitstring is empty.

Definition at line 1012 of file bitstring.py.

1012 def __invert__(self):
1013 """Return bitstring with every bit inverted.
1014
1015 Raises Error if the bitstring is empty.
1016
1017 """
1018 if not self.len:
1019 raise Error("Cannot invert empty bitstring.")
1020 s = self._copy()
1021 s._invert_all()
1022 return s
1023

◆ __le__()

__le__ ( self,
other )
inherited

Definition at line 862 of file bitstring.py.

862 def __le__(self, other):
863 raise TypeError("unorderable type: {0}".format(type(self).__name__))
864

◆ __len__()

__len__ ( self)
inherited
Return the length of the bitstring in bits.

Definition at line 938 of file bitstring.py.

938 def __len__(self):
939 """Return the length of the bitstring in bits."""
940 return self._getlength()
941

◆ __lshift__()

__lshift__ ( self,
n )
inherited
Return bitstring with bits shifted by n to the left.

n -- the number of bits to shift. Must be >= 0.

Definition at line 1024 of file bitstring.py.

1024 def __lshift__(self, n):
1025 """Return bitstring with bits shifted by n to the left.
1026
1027 n -- the number of bits to shift. Must be >= 0.
1028
1029 """
1030 if n < 0:
1031 raise ValueError("Cannot shift by a negative amount.")
1032 if not self.len:
1033 raise ValueError("Cannot shift an empty bitstring.")
1034 n = min(n, self.len)
1035 s = self._slice(n, self.len)
1036 s._append(Bits(n))
1037 return s
1038

◆ __lt__()

__lt__ ( self,
other )
inherited

Definition at line 856 of file bitstring.py.

856 def __lt__(self, other):
857 raise TypeError("unorderable type: {0}".format(type(self).__name__))
858

◆ __mul__()

__mul__ ( self,
n )
inherited
Return bitstring consisting of n concatenations of self.

Called for expression of the form 'a = b*3'.
n -- The number of concatenations. Must be >= 0.

Definition at line 1055 of file bitstring.py.

1055 def __mul__(self, n):
1056 """Return bitstring consisting of n concatenations of self.
1057
1058 Called for expression of the form 'a = b*3'.
1059 n -- The number of concatenations. Must be >= 0.
1060
1061 """
1062 if n < 0:
1063 raise ValueError("Cannot multiply by a negative integer.")
1064 if not n:
1065 return self.__class__()
1066 s = self._copy()
1067 s._imul(n)
1068 return s
1069

◆ __ne__()

__ne__ ( self,
bs )
inherited
Return False if two bitstrings have the same binary representation.

>>> BitArray('0b111') == '0x7'
False

Definition at line 1003 of file bitstring.py.

1003 def __ne__(self, bs):
1004 """Return False if two bitstrings have the same binary representation.
1005
1006 >>> BitArray('0b111') == '0x7'
1007 False
1008
1009 """
1010 return not self.__eq__(bs)
1011

◆ __new__()

__new__ ( cls,
auto = None,
length = None,
offset = None,
** kwargs )

Definition at line 3803 of file bitstring.py.

3803 def __new__(cls, auto=None, length=None, offset=None, **kwargs):
3804 x = super(ConstBitStream, cls).__new__(cls)
3805 x._initialise(auto, length, offset, **kwargs)
3806 return x
3807

◆ __nonzero__()

__nonzero__ ( self)
inherited
Return True if any bits are set to 1, otherwise return False.

Definition at line 1199 of file bitstring.py.

1199 def __nonzero__(self):
1200 """Return True if any bits are set to 1, otherwise return False."""
1201 return self.any(True)
1202

◆ __or__()

__or__ ( self,
bs )
inherited
Bit-wise 'or' between two bitstrings. Returns new bitstring.

bs -- The bitstring to '|' with.

Raises ValueError if the two bitstrings have differing lengths.

Definition at line 1105 of file bitstring.py.

1105 def __or__(self, bs):
1106 """Bit-wise 'or' between two bitstrings. Returns new bitstring.
1107
1108 bs -- The bitstring to '|' with.
1109
1110 Raises ValueError if the two bitstrings have differing lengths.
1111
1112 """
1113 bs = Bits(bs)
1114 if self.len != bs.len:
1115 raise ValueError("Bitstrings must have the same length "
1116 "for | operator.")
1117 s = self._copy()
1118 s._ior(bs)
1119 return s
1120

◆ __radd__()

__radd__ ( self,
bs )
inherited
Append current bitstring to bs and return new bitstring.

bs -- the string for the 'auto' initialiser that will be appended to.

Definition at line 884 of file bitstring.py.

884 def __radd__(self, bs):
885 """Append current bitstring to bs and return new bitstring.
886
887 bs -- the string for the 'auto' initialiser that will be appended to.
888
889 """
890 bs = self._converttobitstring(bs)
891 return bs.__add__(self)
892

◆ __rand__()

__rand__ ( self,
bs )
inherited
Bit-wise 'and' between two bitstrings. Returns new bitstring.

bs -- the bitstring to '&' with.

Raises ValueError if the two bitstrings have differing lengths.

Definition at line 1095 of file bitstring.py.

1095 def __rand__(self, bs):
1096 """Bit-wise 'and' between two bitstrings. Returns new bitstring.
1097
1098 bs -- the bitstring to '&' with.
1099
1100 Raises ValueError if the two bitstrings have differing lengths.
1101
1102 """
1103 return self.__and__(bs)
1104

◆ __repr__()

__repr__ ( self)
inherited
Return representation that could be used to recreate the bitstring.

If the returned string is too long it will be truncated. See __str__().

Definition at line 969 of file bitstring.py.

969 def __repr__(self):
970 """Return representation that could be used to recreate the bitstring.
971
972 If the returned string is too long it will be truncated. See __str__().
973
974 """
975 length = self.len
976 if isinstance(self._datastore._rawarray, MmapByteArray):
977 offsetstring = ''
978 if self._datastore.byteoffset or self._offset:
979 offsetstring = ", offset=%d" % (self._datastore._rawarray.byteoffset * 8 + self._offset)
980 lengthstring = ", length=%d" % length
981 return "{0}(filename='{1}'{2}{3})".format(self.__class__.__name__,
982 self._datastore._rawarray.source.name, lengthstring, offsetstring)
983 else:
984 s = self.__str__()
985 lengthstring = ''
986 if s.endswith('...'):
987 lengthstring = " # length={0}".format(length)
988 return "{0}('{1}'){2}".format(self.__class__.__name__, s, lengthstring)
989

◆ __rmul__()

__rmul__ ( self,
n )
inherited
Return bitstring consisting of n concatenations of self.

Called for expressions of the form 'a = 3*b'.
n -- The number of concatenations. Must be >= 0.

Definition at line 1070 of file bitstring.py.

1070 def __rmul__(self, n):
1071 """Return bitstring consisting of n concatenations of self.
1072
1073 Called for expressions of the form 'a = 3*b'.
1074 n -- The number of concatenations. Must be >= 0.
1075
1076 """
1077 return self.__mul__(n)
1078

◆ __ror__()

__ror__ ( self,
bs )
inherited
Bit-wise 'or' between two bitstrings. Returns new bitstring.

bs -- The bitstring to '|' with.

Raises ValueError if the two bitstrings have differing lengths.

Definition at line 1121 of file bitstring.py.

1121 def __ror__(self, bs):
1122 """Bit-wise 'or' between two bitstrings. Returns new bitstring.
1123
1124 bs -- The bitstring to '|' with.
1125
1126 Raises ValueError if the two bitstrings have differing lengths.
1127
1128 """
1129 return self.__or__(bs)
1130

◆ __rshift__()

__rshift__ ( self,
n )
inherited
Return bitstring with bits shifted by n to the right.

n -- the number of bits to shift. Must be >= 0.

Definition at line 1039 of file bitstring.py.

1039 def __rshift__(self, n):
1040 """Return bitstring with bits shifted by n to the right.
1041
1042 n -- the number of bits to shift. Must be >= 0.
1043
1044 """
1045 if n < 0:
1046 raise ValueError("Cannot shift by a negative amount.")
1047 if not self.len:
1048 raise ValueError("Cannot shift an empty bitstring.")
1049 if not n:
1050 return self._copy()
1051 s = self.__class__(length=min(n, self.len))
1052 s._append(self[:-n])
1053 return s
1054

◆ __rxor__()

__rxor__ ( self,
bs )
inherited
Bit-wise 'xor' between two bitstrings. Returns new bitstring.

bs -- The bitstring to '^' with.

Raises ValueError if the two bitstrings have differing lengths.

Definition at line 1147 of file bitstring.py.

1147 def __rxor__(self, bs):
1148 """Bit-wise 'xor' between two bitstrings. Returns new bitstring.
1149
1150 bs -- The bitstring to '^' with.
1151
1152 Raises ValueError if the two bitstrings have differing lengths.
1153
1154 """
1155 return self.__xor__(bs)
1156

◆ __str__()

__str__ ( self)
inherited
Return approximate string representation of bitstring for printing.

Short strings will be given wholly in hexadecimal or binary. Longer
strings may be part hexadecimal and part binary. Very long strings will
be truncated with '...'.

Definition at line 942 of file bitstring.py.

942 def __str__(self):
943 """Return approximate string representation of bitstring for printing.
944
945 Short strings will be given wholly in hexadecimal or binary. Longer
946 strings may be part hexadecimal and part binary. Very long strings will
947 be truncated with '...'.
948
949 """
950 length = self.len
951 if not length:
952 return ''
953 if length > MAX_CHARS * 4:
954 # Too long for hex. Truncate...
955 return ''.join(('0x', self._readhex(MAX_CHARS * 4, 0), '...'))
956 # If it's quite short and we can't do hex then use bin
957 if length < 32 and length % 4 != 0:
958 return '0b' + self.bin
959 # If we can use hex then do so
960 if not length % 4:
961 return '0x' + self.hex
962 # Otherwise first we do as much as we can in hex
963 # then add on 1, 2 or 3 bits on at the end
964 bits_at_end = length % 4
965 return ''.join(('0x', self._readhex(length - bits_at_end, 0),
966 ', ', '0b',
967 self._readbin(bits_at_end, length - bits_at_end)))
968

◆ __xor__()

__xor__ ( self,
bs )
inherited
Bit-wise 'xor' between two bitstrings. Returns new bitstring.

bs -- The bitstring to '^' with.

Raises ValueError if the two bitstrings have differing lengths.

Definition at line 1131 of file bitstring.py.

1131 def __xor__(self, bs):
1132 """Bit-wise 'xor' between two bitstrings. Returns new bitstring.
1133
1134 bs -- The bitstring to '^' with.
1135
1136 Raises ValueError if the two bitstrings have differing lengths.
1137
1138 """
1139 bs = Bits(bs)
1140 if self.len != bs.len:
1141 raise ValueError("Bitstrings must have the same length "
1142 "for ^ operator.")
1143 s = self._copy()
1144 s._ixor(bs)
1145 return s
1146

◆ _append()

_append ( self,
bs )
protectedinherited
Append a bitstring to the current bitstring.

Definition at line 2035 of file bitstring.py.

2035 def _append(self, bs):
2036 """Append a bitstring to the current bitstring."""
2037 self._datastore._appendstore(bs._datastore)
2038

◆ _assertsanity()

_assertsanity ( self)
protectedinherited
Check internal self consistency as a debugging aid.

Definition at line 1206 of file bitstring.py.

1206 def _assertsanity(self):
1207 """Check internal self consistency as a debugging aid."""
1208 assert self.len >= 0
1209 assert 0 <= self._offset, "offset={0}".format(self._offset)
1210 assert (self.len + self._offset + 7) // 8 == self._datastore.bytelength + self._datastore.byteoffset
1211 return True
1212

◆ _clear()

_clear ( self)
protected
Reset the bitstring to an empty state.

Reimplemented from Bits.

Definition at line 3830 of file bitstring.py.

3830 def _clear(self):
3831 Bits._clear(self)
3832 self._pos = 0
3833

◆ _converttobitstring()

_converttobitstring ( cls,
bs,
offset = 0,
cache = None )
protectedinherited
Convert bs to a bitstring and return it.

offset gives the suggested bit offset of first significant
bit, to optimise append etc.

Definition at line 1966 of file bitstring.py.

1966 def _converttobitstring(cls, bs, offset=0, cache=None):
1967 """Convert bs to a bitstring and return it.
1968
1969 offset gives the suggested bit offset of first significant
1970 bit, to optimise append etc.
1971
1972 """
1973 if cache is None:
1974 cache = {}
1975 if isinstance(bs, Bits):
1976 return bs
1977 try:
1978 return cache[(bs, offset)]
1979 except KeyError:
1980 if isinstance(bs, basestring):
1981 b = cls()
1982 try:
1983 _, tokens = tokenparser(bs)
1984 except ValueError as e:
1985 raise CreationError(*e.args)
1986 if tokens:
1987 b._append(Bits._init_with_token(*tokens[0]))
1988 b._datastore = offsetcopy(b._datastore, offset)
1989 for token in tokens[1:]:
1990 b._append(Bits._init_with_token(*token))
1991 assert b._assertsanity()
1992 assert b.len == 0 or b._offset == offset
1993 if len(cache) < CACHE_SIZE:
1994 cache[(bs, offset)] = b
1995 return b
1996 except TypeError:
1997 # Unhashable type
1998 pass
1999 return cls(bs)
2000

◆ _copy()

_copy ( self)
protectedinherited
Create and return a new copy of the Bits (always in memory).

Definition at line 2001 of file bitstring.py.

2001 def _copy(self):
2002 """Create and return a new copy of the Bits (always in memory)."""
2003 s_copy = self.__class__()
2004 s_copy._setbytes_unsafe(self._datastore.getbyteslice(0, self._datastore.bytelength),
2005 self.len, self._offset)
2006 return s_copy
2007

◆ _delete()

_delete ( self,
bits,
pos )
protectedinherited
Delete bits at pos.

Definition at line 2135 of file bitstring.py.

2135 def _delete(self, bits, pos):
2136 """Delete bits at pos."""
2137 assert 0 <= pos <= self.len
2138 assert pos + bits <= self.len
2139 if not pos:
2140 # Cutting bits off at the start.
2141 self._truncatestart(bits)
2142 return
2143 if pos + bits == self.len:
2144 # Cutting bits off at the end.
2145 self._truncateend(bits)
2146 return
2147 if pos > self.len - pos - bits:
2148 # More bits before cut point than after it, so do bit shifting
2149 # on the final bits.
2150 end = self._slice(pos + bits, self.len)
2151 assert self.len - pos > 0
2152 self._truncateend(self.len - pos)
2153 self._append(end)
2154 return
2155 # More bits after the cut point than before it.
2156 start = self._slice(0, pos)
2157 self._truncatestart(pos + bits)
2158 self._prepend(start)
2159 return
2160

◆ _ensureinmemory()

_ensureinmemory ( self)
protectedinherited
Ensure the data is held in memory, not in a file.

Definition at line 1960 of file bitstring.py.

1960 def _ensureinmemory(self):
1961 """Ensure the data is held in memory, not in a file."""
1962 self._setbytes_unsafe(self._datastore.getbyteslice(0, self._datastore.bytelength),
1963 self.len, self._offset)
1964

◆ _findbytes()

_findbytes ( self,
bytes_,
start,
end,
bytealigned )
protectedinherited
Quicker version of find when everything's whole byte
and byte aligned.

Definition at line 2365 of file bitstring.py.

2365 def _findbytes(self, bytes_, start, end, bytealigned):
2366 """Quicker version of find when everything's whole byte
2367 and byte aligned.
2368
2369 """
2370 assert self._datastore.offset == 0
2371 assert bytealigned is True
2372 # Extract data bytes from bitstring to be found.
2373 bytepos = (start + 7) // 8
2374 found = False
2375 p = bytepos
2376 finalpos = end // 8
2377 increment = max(1024, len(bytes_) * 10)
2378 buffersize = increment + len(bytes_)
2379 while p < finalpos:
2380 # Read in file or from memory in overlapping chunks and search the chunks.
2381 buf = bytearray(self._datastore.getbyteslice(p, min(p + buffersize, finalpos)))
2382 pos = buf.find(bytes_)
2383 if pos != -1:
2384 found = True
2385 p += pos
2386 break
2387 p += increment
2388 if not found:
2389 return ()
2390 return (p * 8,)
2391

◆ _findregex()

_findregex ( self,
reg_ex,
start,
end,
bytealigned )
protectedinherited
Find first occurrence of a compiled regular expression.

Note that this doesn't support arbitrary regexes, in particular they
must match a known length.

Definition at line 2392 of file bitstring.py.

2392 def _findregex(self, reg_ex, start, end, bytealigned):
2393 """Find first occurrence of a compiled regular expression.
2394
2395 Note that this doesn't support arbitrary regexes, in particular they
2396 must match a known length.
2397
2398 """
2399 p = start
2400 length = len(reg_ex.pattern)
2401 # We grab overlapping chunks of the binary representation and
2402 # do an ordinary string search within that.
2403 increment = max(4096, length * 10)
2404 buffersize = increment + length
2405 while p < end:
2406 buf = self._readbin(min(buffersize, end - p), p)
2407 # Test using regular expressions...
2408 m = reg_ex.search(buf)
2409 if m:
2410 pos = m.start()
2411 # pos = buf.find(targetbin)
2412 # if pos != -1:
2413 # if bytealigned then we only accept byte aligned positions.
2414 if not bytealigned or (p + pos) % 8 == 0:
2415 return (p + pos,)
2416 if bytealigned:
2417 # Advance to just beyond the non-byte-aligned match and try again...
2418 p += pos + 1
2419 continue
2420 p += increment
2421 # Not found, return empty tuple
2422 return ()
2423

◆ _getbin()

_getbin ( self)
protectedinherited
Return interpretation as a binary string.

Definition at line 1872 of file bitstring.py.

1872 def _getbin(self):
1873 """Return interpretation as a binary string."""
1874 return self._readbin(self.len, 0)
1875

◆ _getbitpos()

_getbitpos ( self)
protected
Return the current position in the stream in bits.

Definition at line 3826 of file bitstring.py.

3826 def _getbitpos(self):
3827 """Return the current position in the stream in bits."""
3828 return self._pos
3829

◆ _getbool()

_getbool ( self)
protectedinherited

Definition at line 1825 of file bitstring.py.

1825 def _getbool(self):
1826 if self.length != 1:
1827 msg = "For a bool interpretation a bitstring must be 1 bit long, not {0} bits."
1828 raise InterpretError(msg, self.length)
1829 return self[0]
1830

◆ _getbytepos()

_getbytepos ( self)
protected
Return the current position in the stream in bytes. Must be byte aligned.

Definition at line 3812 of file bitstring.py.

3812 def _getbytepos(self):
3813 """Return the current position in the stream in bytes. Must be byte aligned."""
3814 if self._pos % 8:
3815 raise ByteAlignError("Not byte aligned in _getbytepos().")
3816 return self._pos // 8
3817

◆ _getbytes()

_getbytes ( self)
protectedinherited
Return the data as an ordinary string.

Definition at line 1355 of file bitstring.py.

1355 def _getbytes(self):
1356 """Return the data as an ordinary string."""
1357 if self.len % 8:
1358 raise InterpretError("Cannot interpret as bytes unambiguously - "
1359 "not multiple of 8 bits.")
1360 return self._readbytes(self.len, 0)
1361

◆ _getfloat()

_getfloat ( self)
protectedinherited
Interpret the whole bitstring as a float.

Definition at line 1586 of file bitstring.py.

1586 def _getfloat(self):
1587 """Interpret the whole bitstring as a float."""
1588 return self._readfloat(self.len, 0)
1589

◆ _getfloatle()

_getfloatle ( self)
protectedinherited
Interpret the whole bitstring as a little-endian float.

Definition at line 1625 of file bitstring.py.

1625 def _getfloatle(self):
1626 """Interpret the whole bitstring as a little-endian float."""
1627 return self._readfloatle(self.len, 0)
1628

◆ _gethex()

_gethex ( self)
protectedinherited
Return the hexadecimal representation as a string prefixed with '0x'.

Raises an InterpretError if the bitstring's length is not a multiple of 4.

Definition at line 1945 of file bitstring.py.

1945 def _gethex(self):
1946 """Return the hexadecimal representation as a string prefixed with '0x'.
1947
1948 Raises an InterpretError if the bitstring's length is not a multiple of 4.
1949
1950 """
1951 return self._readhex(self.len, 0)
1952

◆ _getint()

_getint ( self)
protectedinherited
Return data as a two's complement signed int.

Definition at line 1454 of file bitstring.py.

1454 def _getint(self):
1455 """Return data as a two's complement signed int."""
1456 return self._readint(self.len, 0)
1457

◆ _getintbe()

_getintbe ( self)
protectedinherited
Return data as a big-endian two's complement signed int.

Definition at line 1490 of file bitstring.py.

1490 def _getintbe(self):
1491 """Return data as a big-endian two's complement signed int."""
1492 return self._readintbe(self.len, 0)
1493

◆ _getintle()

_getintle ( self)
protectedinherited

Definition at line 1549 of file bitstring.py.

1549 def _getintle(self):
1550 return self._readintle(self.len, 0)
1551

◆ _getlength()

_getlength ( self)
protectedinherited
Return the length of the bitstring in bits.

Definition at line 1956 of file bitstring.py.

1956 def _getlength(self):
1957 """Return the length of the bitstring in bits."""
1958 return self._datastore.bitlength
1959

◆ _getoct()

_getoct ( self)
protectedinherited
Return interpretation as an octal string.

Definition at line 1906 of file bitstring.py.

1906 def _getoct(self):
1907 """Return interpretation as an octal string."""
1908 return self._readoct(self.len, 0)
1909

◆ _getoffset()

_getoffset ( self)
protectedinherited

Definition at line 1953 of file bitstring.py.

1953 def _getoffset(self):
1954 return self._datastore.offset
1955

◆ _getse()

_getse ( self)
protectedinherited
Return data as signed exponential-Golomb code.

Raises InterpretError if bitstring is not a single exponential-Golomb code.

Definition at line 1698 of file bitstring.py.

1698 def _getse(self):
1699 """Return data as signed exponential-Golomb code.
1700
1701 Raises InterpretError if bitstring is not a single exponential-Golomb code.
1702
1703 """
1704 try:
1705 value, newpos = self._readse(0)
1706 if value is None or newpos != self.len:
1707 raise ReadError
1708 except ReadError:
1709 raise InterpretError("Bitstring is not a single exponential-Golomb code.")
1710 return value
1711

◆ _getsie()

_getsie ( self)
protectedinherited
Return data as signed interleaved exponential-Golomb code.

Raises InterpretError if bitstring is not a single exponential-Golomb code.

Definition at line 1781 of file bitstring.py.

1781 def _getsie(self):
1782 """Return data as signed interleaved exponential-Golomb code.
1783
1784 Raises InterpretError if bitstring is not a single exponential-Golomb code.
1785
1786 """
1787 try:
1788 value, newpos = self._readsie(0)
1789 if value is None or newpos != self.len:
1790 raise ReadError
1791 except ReadError:
1792 raise InterpretError("Bitstring is not a single interleaved exponential-Golomb code.")
1793 return value
1794

◆ _getue()

_getue ( self)
protectedinherited
Return data as unsigned exponential-Golomb code.

Raises InterpretError if bitstring is not a single exponential-Golomb code.

Definition at line 1676 of file bitstring.py.

1676 def _getue(self):
1677 """Return data as unsigned exponential-Golomb code.
1678
1679 Raises InterpretError if bitstring is not a single exponential-Golomb code.
1680
1681 """
1682 try:
1683 value, newpos = self._readue(0)
1684 if value is None or newpos != self.len:
1685 raise ReadError
1686 except ReadError:
1687 raise InterpretError("Bitstring is not a single exponential-Golomb code.")
1688 return value
1689

◆ _getuie()

_getuie ( self)
protectedinherited
Return data as unsigned interleaved exponential-Golomb code.

Raises InterpretError if bitstring is not a single exponential-Golomb code.

Definition at line 1759 of file bitstring.py.

1759 def _getuie(self):
1760 """Return data as unsigned interleaved exponential-Golomb code.
1761
1762 Raises InterpretError if bitstring is not a single exponential-Golomb code.
1763
1764 """
1765 try:
1766 value, newpos = self._readuie(0)
1767 if value is None or newpos != self.len:
1768 raise ReadError
1769 except ReadError:
1770 raise InterpretError("Bitstring is not a single interleaved exponential-Golomb code.")
1771 return value
1772

◆ _getuint()

_getuint ( self)
protectedinherited
Return data as an unsigned int.

Definition at line 1417 of file bitstring.py.

1417 def _getuint(self):
1418 """Return data as an unsigned int."""
1419 return self._readuint(self.len, 0)
1420

◆ _getuintbe()

_getuintbe ( self)
protectedinherited
Return data as a big-endian two's complement unsigned int.

Definition at line 1472 of file bitstring.py.

1472 def _getuintbe(self):
1473 """Return data as a big-endian two's complement unsigned int."""
1474 return self._readuintbe(self.len, 0)
1475

◆ _getuintle()

_getuintle ( self)
protectedinherited

Definition at line 1529 of file bitstring.py.

1529 def _getuintle(self):
1530 return self._readuintle(self.len, 0)
1531

◆ _iand()

_iand ( self,
bs )
protectedinherited

Definition at line 2243 of file bitstring.py.

2243 def _iand(self, bs):
2244 return self._inplace_logical_helper(bs, operator.iand)
2245

◆ _ilshift()

_ilshift ( self,
n )
protectedinherited
Shift bits by n to the left in place. Return self.

Definition at line 2196 of file bitstring.py.

2196 def _ilshift(self, n):
2197 """Shift bits by n to the left in place. Return self."""
2198 assert 0 < n <= self.len
2199 self._append(Bits(n))
2200 self._truncatestart(n)
2201 return self
2202

◆ _imul()

_imul ( self,
n )
protectedinherited
Concatenate n copies of self in place. Return self.

Definition at line 2210 of file bitstring.py.

2210 def _imul(self, n):
2211 """Concatenate n copies of self in place. Return self."""
2212 assert n >= 0
2213 if not n:
2214 self._clear()
2215 return self
2216 m = 1
2217 old_len = self.len
2218 while m * 2 < n:
2219 self._append(self)
2220 m *= 2
2221 self._append(self[0:(n - m) * old_len])
2222 return self
2223

◆ _init_with_token()

_init_with_token ( cls,
name,
token_length,
value )
protectedinherited

Definition at line 1214 of file bitstring.py.

1214 def _init_with_token(cls, name, token_length, value):
1215 if token_length is not None:
1216 token_length = int(token_length)
1217 if token_length == 0:
1218 return cls()
1219 # For pad token just return the length in zero bits
1220 if name == 'pad':
1221 return cls(token_length)
1222
1223 if value is None:
1224 if token_length is None:
1225 error = "Token has no value ({0}=???).".format(name)
1226 else:
1227 error = "Token has no value ({0}:{1}=???).".format(name, token_length)
1228 raise ValueError(error)
1229 try:
1230 b = cls(**{_tokenname_to_initialiser[name]: value})
1231 except KeyError:
1232 if name in ('se', 'ue', 'sie', 'uie'):
1233 b = cls(**{name: int(value)})
1234 elif name in ('uint', 'int', 'uintbe', 'intbe', 'uintle', 'intle', 'uintne', 'intne'):
1235 b = cls(**{name: int(value), 'length': token_length})
1236 elif name in ('float', 'floatbe', 'floatle', 'floatne'):
1237 b = cls(**{name: float(value), 'length': token_length})
1238 elif name == 'bool':
1239 if value in (1, 'True', '1'):
1240 b = cls(bool=True)
1241 elif value in (0, 'False', '0'):
1242 b = cls(bool=False)
1243 else:
1244 raise CreationError("bool token can only be 'True' or 'False'.")
1245 else:
1246 raise CreationError("Can't parse token name {0}.", name)
1247 if token_length is not None and b.len != token_length:
1248 msg = "Token with length {0} packed with value of length {1} ({2}:{3}={4})."
1249 raise CreationError(msg, token_length, b.len, name, token_length, value)
1250 return b
1251

◆ _initialise()

_initialise ( self,
auto,
length,
offset,
** kwargs )
protectedinherited

Definition at line 810 of file bitstring.py.

810 def _initialise(self, auto, length, offset, **kwargs):
811 if length is not None and length < 0:
812 raise CreationError("bitstring length cannot be negative.")
813 if offset is not None and offset < 0:
814 raise CreationError("offset must be >= 0.")
815 if auto is not None:
816 self._initialise_from_auto(auto, length, offset)
817 return
818 if not kwargs:
819 # No initialisers, so initialise with nothing or zero bits
820 if length is not None and length != 0:
821 data = bytearray((length + 7) // 8)
822 self._setbytes_unsafe(data, length, 0)
823 return
824 self._setbytes_unsafe(bytearray(0), 0, 0)
825 return
826 k, v = kwargs.popitem()
827 try:
828 init_without_length_or_offset[k](self, v)
829 if length is not None or offset is not None:
830 raise CreationError("Cannot use length or offset with this initialiser.")
831 except KeyError:
832 try:
833 init_with_length_only[k](self, v, length)
834 if offset is not None:
835 raise CreationError("Cannot use offset with this initialiser.")
836 except KeyError:
837 if offset is None:
838 offset = 0
839 try:
840 init_with_length_and_offset[k](self, v, length, offset)
841 except KeyError:
842 raise CreationError("Unrecognised keyword '{0}' used to initialise.", k)
843

◆ _initialise_from_auto()

_initialise_from_auto ( self,
auto,
length,
offset )
protectedinherited

Definition at line 844 of file bitstring.py.

844 def _initialise_from_auto(self, auto, length, offset):
845 if offset is None:
846 offset = 0
847 self._setauto(auto, length, offset)
848 return
849

◆ _inplace_logical_helper()

_inplace_logical_helper ( self,
bs,
f )
protectedinherited
Helper function containing most of the __ior__, __iand__, __ixor__ code.

Definition at line 2224 of file bitstring.py.

2224 def _inplace_logical_helper(self, bs, f):
2225 """Helper function containing most of the __ior__, __iand__, __ixor__ code."""
2226 # Give the two bitstrings the same offset (modulo 8)
2227 self_byteoffset, self_bitoffset = divmod(self._offset, 8)
2228 bs_byteoffset, bs_bitoffset = divmod(bs._offset, 8)
2229 if bs_bitoffset != self_bitoffset:
2230 if not self_bitoffset:
2231 bs._datastore = offsetcopy(bs._datastore, 0)
2232 else:
2233 self._datastore = offsetcopy(self._datastore, bs_bitoffset)
2234 a = self._datastore.rawbytes
2235 b = bs._datastore.rawbytes
2236 for i in xrange(len(a)):
2237 a[i] = f(a[i + self_byteoffset], b[i + bs_byteoffset])
2238 return self
2239

◆ _insert()

_insert ( self,
bs,
pos )
protectedinherited
Insert bs at pos.

Definition at line 2081 of file bitstring.py.

2081 def _insert(self, bs, pos):
2082 """Insert bs at pos."""
2083 assert 0 <= pos <= self.len
2084 if pos > self.len // 2:
2085 # Inserting nearer end, so cut off end.
2086 end = self._slice(pos, self.len)
2087 self._truncateend(self.len - pos)
2088 self._append(bs)
2089 self._append(end)
2090 else:
2091 # Inserting nearer start, so cut off start.
2092 start = self._slice(0, pos)
2093 self._truncatestart(pos)
2094 self._prepend(bs)
2095 self._prepend(start)
2096 try:
2097 self._pos = pos + bs.len
2098 except AttributeError:
2099 pass
2100 assert self._assertsanity()
2101

◆ _invert()

_invert ( self,
pos )
protectedinherited
Flip bit at pos 1<->0.

Definition at line 2184 of file bitstring.py.

2184 def _invert(self, pos):
2185 """Flip bit at pos 1<->0."""
2186 assert 0 <= pos < self.len
2187 self._datastore.invertbit(pos)
2188

◆ _invert_all()

_invert_all ( self)
protectedinherited
Invert every bit.

Definition at line 2189 of file bitstring.py.

2189 def _invert_all(self):
2190 """Invert every bit."""
2191 set = self._datastore.setbyte
2192 get = self._datastore.getbyte
2193 for p in xrange(self._datastore.byteoffset, self._datastore.byteoffset + self._datastore.bytelength):
2194 set(p, 256 + ~get(p))
2195

◆ _ior()

_ior ( self,
bs )
protectedinherited

Definition at line 2240 of file bitstring.py.

2240 def _ior(self, bs):
2241 return self._inplace_logical_helper(bs, operator.ior)
2242

◆ _irshift()

_irshift ( self,
n )
protectedinherited
Shift bits by n to the right in place. Return self.

Definition at line 2203 of file bitstring.py.

2203 def _irshift(self, n):
2204 """Shift bits by n to the right in place. Return self."""
2205 assert 0 < n <= self.len
2206 self._prepend(Bits(n))
2207 self._truncateend(n)
2208 return self
2209

◆ _ixor()

_ixor ( self,
bs )
protectedinherited

Definition at line 2246 of file bitstring.py.

2246 def _ixor(self, bs):
2247 return self._inplace_logical_helper(bs, operator.xor)
2248

◆ _overwrite()

_overwrite ( self,
bs,
pos )
protectedinherited
Overwrite with bs at pos.

Definition at line 2102 of file bitstring.py.

2102 def _overwrite(self, bs, pos):
2103 """Overwrite with bs at pos."""
2104 assert 0 <= pos < self.len
2105 if bs is self:
2106 # Just overwriting with self, so do nothing.
2107 assert pos == 0
2108 return
2109 firstbytepos = (self._offset + pos) // 8
2110 lastbytepos = (self._offset + pos + bs.len - 1) // 8
2111 bytepos, bitoffset = divmod(self._offset + pos, 8)
2112 if firstbytepos == lastbytepos:
2113 mask = ((1 << bs.len) - 1) << (8 - bs.len - bitoffset)
2114 self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) & (~mask))
2115 d = offsetcopy(bs._datastore, bitoffset)
2116 self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) | (d.getbyte(0) & mask))
2117 else:
2118 # Do first byte
2119 mask = (1 << (8 - bitoffset)) - 1
2120 self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) & (~mask))
2121 d = offsetcopy(bs._datastore, bitoffset)
2122 self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) | (d.getbyte(0) & mask))
2123 # Now do all the full bytes
2124 self._datastore.setbyteslice(firstbytepos + 1, lastbytepos, d.getbyteslice(1, lastbytepos - firstbytepos))
2125 # and finally the last byte
2126 bitsleft = (self._offset + pos + bs.len) % 8
2127 if not bitsleft:
2128 bitsleft = 8
2129 mask = (1 << (8 - bitsleft)) - 1
2130 self._datastore.setbyte(lastbytepos, self._datastore.getbyte(lastbytepos) & mask)
2131 self._datastore.setbyte(lastbytepos,
2132 self._datastore.getbyte(lastbytepos) | (d.getbyte(d.bytelength - 1) & ~mask))
2133 assert self._assertsanity()
2134

◆ _prepend()

_prepend ( self,
bs )
protectedinherited
Prepend a bitstring to the current bitstring.

Definition at line 2039 of file bitstring.py.

2039 def _prepend(self, bs):
2040 """Prepend a bitstring to the current bitstring."""
2041 self._datastore._prependstore(bs._datastore)
2042

◆ _readbin()

_readbin ( self,
length,
start )
protectedinherited
Read bits and interpret as a binary string.

Definition at line 1855 of file bitstring.py.

1855 def _readbin(self, length, start):
1856 """Read bits and interpret as a binary string."""
1857 if not length:
1858 return ''
1859 # Get the byte slice containing our bit slice
1860 startbyte, startoffset = divmod(start + self._offset, 8)
1861 endbyte = (start + self._offset + length - 1) // 8
1862 b = self._datastore.getbyteslice(startbyte, endbyte + 1)
1863 # Convert to a string of '0' and '1's (via a hex string an and int!)
1864 try:
1865 c = "{:0{}b}".format(int(binascii.hexlify(b), 16), 8 * len(b))
1866 except TypeError:
1867 # Hack to get Python 2.6 working
1868 c = "{0:0{1}b}".format(int(binascii.hexlify(str(b)), 16), 8 * len(b))
1869 # Finally chop off any extra bits.
1870 return c[startoffset:startoffset + length]
1871

◆ _readbits()

_readbits ( self,
length,
start )
protectedinherited
Read some bits from the bitstring and return newly constructed bitstring.

Definition at line 2249 of file bitstring.py.

2249 def _readbits(self, length, start):
2250 """Read some bits from the bitstring and return newly constructed bitstring."""
2251 return self._slice(start, start + length)
2252

◆ _readbool()

_readbool ( self,
pos )
protectedinherited

Definition at line 1831 of file bitstring.py.

1831 def _readbool(self, pos):
1832 return self[pos], pos + 1
1833

◆ _readbytes()

_readbytes ( self,
length,
start )
protectedinherited
Read bytes and return them. Note that length is in bits.

Definition at line 1346 of file bitstring.py.

1346 def _readbytes(self, length, start):
1347 """Read bytes and return them. Note that length is in bits."""
1348 assert length % 8 == 0
1349 assert start + length <= self.len
1350 if not (start + self._offset) % 8:
1351 return bytes(self._datastore.getbyteslice((start + self._offset) // 8,
1352 (start + self._offset + length) // 8))
1353 return self._slice(start, start + length).tobytes()
1354

◆ _readfloat()

_readfloat ( self,
length,
start )
protectedinherited
Read bits and interpret as a float.

Definition at line 1568 of file bitstring.py.

1568 def _readfloat(self, length, start):
1569 """Read bits and interpret as a float."""
1570 if not (start + self._offset) % 8:
1571 startbyte = (start + self._offset) // 8
1572 if length == 32:
1573 f, = struct.unpack('>f', bytes(self._datastore.getbyteslice(startbyte, startbyte + 4)))
1574 elif length == 64:
1575 f, = struct.unpack('>d', bytes(self._datastore.getbyteslice(startbyte, startbyte + 8)))
1576 else:
1577 if length == 32:
1578 f, = struct.unpack('>f', self._readbytes(32, start))
1579 elif length == 64:
1580 f, = struct.unpack('>d', self._readbytes(64, start))
1581 try:
1582 return f
1583 except NameError:
1584 raise InterpretError("floats can only be 32 or 64 bits long, not {0} bits", length)
1585

◆ _readfloatle()

_readfloatle ( self,
length,
start )
protectedinherited
Read bits and interpret as a little-endian float.

Definition at line 1606 of file bitstring.py.

1606 def _readfloatle(self, length, start):
1607 """Read bits and interpret as a little-endian float."""
1608 startbyte, offset = divmod(start + self._offset, 8)
1609 if not offset:
1610 if length == 32:
1611 f, = struct.unpack('<f', bytes(self._datastore.getbyteslice(startbyte, startbyte + 4)))
1612 elif length == 64:
1613 f, = struct.unpack('<d', bytes(self._datastore.getbyteslice(startbyte, startbyte + 8)))
1614 else:
1615 if length == 32:
1616 f, = struct.unpack('<f', self._readbytes(32, start))
1617 elif length == 64:
1618 f, = struct.unpack('<d', self._readbytes(64, start))
1619 try:
1620 return f
1621 except NameError:
1622 raise InterpretError("floats can only be 32 or 64 bits long, "
1623 "not {0} bits", length)
1624

◆ _readhex()

_readhex ( self,
length,
start )
protectedinherited
Read bits and interpret as a hex string.

Definition at line 1928 of file bitstring.py.

1928 def _readhex(self, length, start):
1929 """Read bits and interpret as a hex string."""
1930 if length % 4:
1931 raise InterpretError("Cannot convert to hex unambiguously - "
1932 "not multiple of 4 bits.")
1933 if not length:
1934 return ''
1935 s = self._slice(start, start + length).tobytes()
1936 try:
1937 s = s.hex() # Available in Python 3.5
1938 except AttributeError:
1939 # This monstrosity is the only thing I could get to work for both 2.6 and 3.1.
1940 # TODO: Is utf-8 really what we mean here?
1941 s = str(binascii.hexlify(s).decode('utf-8'))
1942 # If there's one nibble too many then cut it off
1943 return s[:-1] if (length // 4) % 2 else s
1944

◆ _readint()

_readint ( self,
length,
start )
protectedinherited
Read bits and interpret as a signed int

Definition at line 1444 of file bitstring.py.

1444 def _readint(self, length, start):
1445 """Read bits and interpret as a signed int"""
1446 ui = self._readuint(length, start)
1447 if not ui >> (length - 1):
1448 # Top bit not set, number is positive
1449 return ui
1450 # Top bit is set, so number is negative
1451 tmp = (~(ui - 1)) & ((1 << length) - 1)
1452 return -tmp
1453

◆ _readintbe()

_readintbe ( self,
length,
start )
protectedinherited
Read bits and interpret as a big-endian signed int.

Definition at line 1483 of file bitstring.py.

1483 def _readintbe(self, length, start):
1484 """Read bits and interpret as a big-endian signed int."""
1485 if length % 8:
1486 raise InterpretError("Big-endian integers must be whole-byte. "
1487 "Length = {0} bits.", length)
1488 return self._readint(length, start)
1489

◆ _readintle()

_readintle ( self,
length,
start )
protectedinherited
Read bits and interpret as a little-endian signed int.

Definition at line 1539 of file bitstring.py.

1539 def _readintle(self, length, start):
1540 """Read bits and interpret as a little-endian signed int."""
1541 ui = self._readuintle(length, start)
1542 if not ui >> (length - 1):
1543 # Top bit not set, number is positive
1544 return ui
1545 # Top bit is set, so number is negative
1546 tmp = (~(ui - 1)) & ((1 << length) - 1)
1547 return -tmp
1548

◆ _readlist()

_readlist ( self,
fmt,
pos,
** kwargs )
protectedinherited

Definition at line 2288 of file bitstring.py.

2288 def _readlist(self, fmt, pos, **kwargs):
2289 tokens = []
2290 stretchy_token = None
2291 if isinstance(fmt, basestring):
2292 fmt = [fmt]
2293 # Not very optimal this, but replace integers with 'bits' tokens
2294 # TODO: optimise
2295 for i, f in enumerate(fmt):
2296 if isinstance(f, numbers.Integral):
2297 fmt[i] = "bits:{0}".format(f)
2298 for f_item in fmt:
2299 stretchy, tkns = tokenparser(f_item, tuple(sorted(kwargs.keys())))
2300 if stretchy:
2301 if stretchy_token:
2302 raise Error("It's not possible to have more than one 'filler' token.")
2303 stretchy_token = stretchy
2304 tokens.extend(tkns)
2305 if not stretchy_token:
2306 lst = []
2307 for name, length, _ in tokens:
2308 if length in kwargs:
2309 length = kwargs[length]
2310 if name == 'bytes':
2311 length *= 8
2312 if name in kwargs and length is None:
2313 # Using default 'uint' - the name is really the length.
2314 value, pos = self._readtoken('uint', pos, kwargs[name])
2315 lst.append(value)
2316 continue
2317 value, pos = self._readtoken(name, pos, length)
2318 if value is not None: # Don't append pad tokens
2319 lst.append(value)
2320 return lst, pos
2321 stretchy_token = False
2322 bits_after_stretchy_token = 0
2323 for token in tokens:
2324 name, length, _ = token
2325 if length in kwargs:
2326 length = kwargs[length]
2327 if name == 'bytes':
2328 length *= 8
2329 if name in kwargs and length is None:
2330 # Default 'uint'.
2331 length = kwargs[name]
2332 if stretchy_token:
2333 if name in ('se', 'ue', 'sie', 'uie'):
2334 raise Error("It's not possible to parse a variable"
2335 "length token after a 'filler' token.")
2336 else:
2337 if length is None:
2338 raise Error("It's not possible to have more than "
2339 "one 'filler' token.")
2340 bits_after_stretchy_token += length
2341 if length is None and name not in ('se', 'ue', 'sie', 'uie'):
2342 assert not stretchy_token
2343 stretchy_token = token
2344 bits_left = self.len - pos
2345 return_values = []
2346 for token in tokens:
2347 name, length, _ = token
2348 if token is stretchy_token:
2349 # Set length to the remaining bits
2350 length = max(bits_left - bits_after_stretchy_token, 0)
2351 if length in kwargs:
2352 length = kwargs[length]
2353 if name == 'bytes':
2354 length *= 8
2355 if name in kwargs and length is None:
2356 # Default 'uint'
2357 length = kwargs[name]
2358 if length is not None:
2359 bits_left -= length
2360 value, pos = self._readtoken(name, pos, length)
2361 if value is not None:
2362 return_values.append(value)
2363 return return_values, pos
2364

◆ _readoct()

_readoct ( self,
length,
start )
protectedinherited
Read bits and interpret as an octal string.

Definition at line 1891 of file bitstring.py.

1891 def _readoct(self, length, start):
1892 """Read bits and interpret as an octal string."""
1893 if length % 3:
1894 raise InterpretError("Cannot convert to octal unambiguously - "
1895 "not multiple of 3 bits.")
1896 if not length:
1897 return ''
1898 # Get main octal bit by converting from int.
1899 # Strip starting 0 or 0o depending on Python version.
1900 end = oct(self._readuint(length, start))[LEADING_OCT_CHARS:]
1901 if end.endswith('L'):
1902 end = end[:-1]
1903 middle = '0' * (length // 3 - len(end))
1904 return middle + end
1905

◆ _readse()

_readse ( self,
pos )
protectedinherited
Return interpretation of next bits as a signed exponential-Golomb code.

Advances position to after the read code.

Raises ReadError if the end of the bitstring is encountered while
reading the code.

Definition at line 1712 of file bitstring.py.

1712 def _readse(self, pos):
1713 """Return interpretation of next bits as a signed exponential-Golomb code.
1714
1715 Advances position to after the read code.
1716
1717 Raises ReadError if the end of the bitstring is encountered while
1718 reading the code.
1719
1720 """
1721 codenum, pos = self._readue(pos)
1722 m = (codenum + 1) // 2
1723 if not codenum % 2:
1724 return -m, pos
1725 else:
1726 return m, pos
1727

◆ _readsie()

_readsie ( self,
pos )
protectedinherited
Return interpretation of next bits as a signed interleaved exponential-Golomb code.

Advances position to after the read code.

Raises ReadError if the end of the bitstring is encountered while
reading the code.

Definition at line 1795 of file bitstring.py.

1795 def _readsie(self, pos):
1796 """Return interpretation of next bits as a signed interleaved exponential-Golomb code.
1797
1798 Advances position to after the read code.
1799
1800 Raises ReadError if the end of the bitstring is encountered while
1801 reading the code.
1802
1803 """
1804 codenum, pos = self._readuie(pos)
1805 if not codenum:
1806 return 0, pos
1807 try:
1808 if self[pos]:
1809 return -codenum, pos + 1
1810 else:
1811 return codenum, pos + 1
1812 except IndexError:
1813 raise ReadError("Read off end of bitstring trying to read code.")
1814

◆ _readtoken()

_readtoken ( self,
name,
pos,
length )
protectedinherited
Reads a token from the bitstring and returns the result.

Definition at line 2019 of file bitstring.py.

2019 def _readtoken(self, name, pos, length):
2020 """Reads a token from the bitstring and returns the result."""
2021 if length is not None and int(length) > self.length - pos:
2022 raise ReadError("Reading off the end of the data. "
2023 "Tried to read {0} bits when only {1} available.".format(int(length), self.length - pos))
2024 try:
2025 val = name_to_read[name](self, length, pos)
2026 return val, pos + length
2027 except KeyError:
2028 if name == 'pad':
2029 return None, pos + length
2030 raise ValueError("Can't parse token {0}:{1}".format(name, length))
2031 except TypeError:
2032 # This is for the 'ue', 'se' and 'bool' tokens. They will also return the new pos.
2033 return name_to_read[name](self, pos)
2034

◆ _readue()

_readue ( self,
pos )
protectedinherited
Return interpretation of next bits as unsigned exponential-Golomb code.

Raises ReadError if the end of the bitstring is encountered while
reading the code.

Definition at line 1651 of file bitstring.py.

1651 def _readue(self, pos):
1652 """Return interpretation of next bits as unsigned exponential-Golomb code.
1653
1654 Raises ReadError if the end of the bitstring is encountered while
1655 reading the code.
1656
1657 """
1658 oldpos = pos
1659 try:
1660 while not self[pos]:
1661 pos += 1
1662 except IndexError:
1663 raise ReadError("Read off end of bitstring trying to read code.")
1664 leadingzeros = pos - oldpos
1665 codenum = (1 << leadingzeros) - 1
1666 if leadingzeros > 0:
1667 if pos + leadingzeros + 1 > self.len:
1668 raise ReadError("Read off end of bitstring trying to read code.")
1669 codenum += self._readuint(leadingzeros, pos + 1)
1670 pos += leadingzeros + 1
1671 else:
1672 assert codenum == 0
1673 pos += 1
1674 return codenum, pos
1675

◆ _readuie()

_readuie ( self,
pos )
protectedinherited
Return interpretation of next bits as unsigned interleaved exponential-Golomb code.

Raises ReadError if the end of the bitstring is encountered while
reading the code.

Definition at line 1739 of file bitstring.py.

1739 def _readuie(self, pos):
1740 """Return interpretation of next bits as unsigned interleaved exponential-Golomb code.
1741
1742 Raises ReadError if the end of the bitstring is encountered while
1743 reading the code.
1744
1745 """
1746 try:
1747 codenum = 1
1748 while not self[pos]:
1749 pos += 1
1750 codenum <<= 1
1751 codenum += self[pos]
1752 pos += 1
1753 pos += 1
1754 except IndexError:
1755 raise ReadError("Read off end of bitstring trying to read code.")
1756 codenum -= 1
1757 return codenum, pos
1758

◆ _readuint()

_readuint ( self,
length,
start )
protectedinherited
Read bits and interpret as an unsigned int.

Definition at line 1399 of file bitstring.py.

1399 def _readuint(self, length, start):
1400 """Read bits and interpret as an unsigned int."""
1401 if not length:
1402 raise InterpretError("Cannot interpret a zero length bitstring "
1403 "as an integer.")
1404 offset = self._offset
1405 startbyte = (start + offset) // 8
1406 endbyte = (start + offset + length - 1) // 8
1407
1408 b = binascii.hexlify(bytes(self._datastore.getbyteslice(startbyte, endbyte + 1)))
1409 assert b
1410 i = int(b, 16)
1411 final_bits = 8 - ((start + offset + length) % 8)
1412 if final_bits != 8:
1413 i >>= final_bits
1414 i &= (1 << length) - 1
1415 return i
1416

◆ _readuintbe()

_readuintbe ( self,
length,
start )
protectedinherited
Read bits and interpret as a big-endian unsigned int.

Definition at line 1465 of file bitstring.py.

1465 def _readuintbe(self, length, start):
1466 """Read bits and interpret as a big-endian unsigned int."""
1467 if length % 8:
1468 raise InterpretError("Big-endian integers must be whole-byte. "
1469 "Length = {0} bits.", length)
1470 return self._readuint(length, start)
1471

◆ _readuintle()

_readuintle ( self,
length,
start )
protectedinherited
Read bits and interpret as a little-endian unsigned int.

Definition at line 1501 of file bitstring.py.

1501 def _readuintle(self, length, start):
1502 """Read bits and interpret as a little-endian unsigned int."""
1503 if length % 8:
1504 raise InterpretError("Little-endian integers must be whole-byte. "
1505 "Length = {0} bits.", length)
1506 assert start + length <= self.len
1507 absolute_pos = start + self._offset
1508 startbyte, offset = divmod(absolute_pos, 8)
1509 val = 0
1510 if not offset:
1511 endbyte = (absolute_pos + length - 1) // 8
1512 chunksize = 4 # for 'L' format
1513 while endbyte - chunksize + 1 >= startbyte:
1514 val <<= 8 * chunksize
1515 val += struct.unpack('<L', bytes(self._datastore.getbyteslice(endbyte + 1 - chunksize, endbyte + 1)))[0]
1516 endbyte -= chunksize
1517 for b in xrange(endbyte, startbyte - 1, -1):
1518 val <<= 8
1519 val += self._datastore.getbyte(b)
1520 else:
1521 data = self._slice(start, start + length)
1522 assert data.len % 8 == 0
1523 data._reversebytes(0, self.len)
1524 for b in bytearray(data.bytes):
1525 val <<= 8
1526 val += b
1527 return val
1528

◆ _reverse()

_reverse ( self)
protectedinherited
Reverse all bits in-place.

Definition at line 2043 of file bitstring.py.

2043 def _reverse(self):
2044 """Reverse all bits in-place."""
2045 # Reverse the contents of each byte
2046 n = [BYTE_REVERSAL_DICT[b] for b in self._datastore.rawbytes]
2047 # Then reverse the order of the bytes
2048 n.reverse()
2049 # The new offset is the number of bits that were unused at the end.
2050 newoffset = 8 - (self._offset + self.len) % 8
2051 if newoffset == 8:
2052 newoffset = 0
2053 self._setbytes_unsafe(bytearray().join(n), self.length, newoffset)
2054

◆ _reversebytes()

_reversebytes ( self,
start,
end )
protectedinherited
Reverse bytes in-place.

Definition at line 2161 of file bitstring.py.

2161 def _reversebytes(self, start, end):
2162 """Reverse bytes in-place."""
2163 # Make the start occur on a byte boundary
2164 # TODO: We could be cleverer here to avoid changing the offset.
2165 newoffset = 8 - (start % 8)
2166 if newoffset == 8:
2167 newoffset = 0
2168 self._datastore = offsetcopy(self._datastore, newoffset)
2169 # Now just reverse the byte data
2170 toreverse = bytearray(self._datastore.getbyteslice((newoffset + start) // 8, (newoffset + end) // 8))
2171 toreverse.reverse()
2172 self._datastore.setbyteslice((newoffset + start) // 8, (newoffset + end) // 8, toreverse)
2173

◆ _set()

_set ( self,
pos )
protectedinherited
Set bit at pos to 1.

Definition at line 2174 of file bitstring.py.

2174 def _set(self, pos):
2175 """Set bit at pos to 1."""
2176 assert 0 <= pos < self.len
2177 self._datastore.setbit(pos)
2178

◆ _setauto()

_setauto ( self,
s,
length,
offset )
protectedinherited
Set bitstring from a bitstring, file, bool, integer, array, iterable or string.

Definition at line 1256 of file bitstring.py.

1256 def _setauto(self, s, length, offset):
1257 """Set bitstring from a bitstring, file, bool, integer, array, iterable or string."""
1258 # As s can be so many different things it's important to do the checks
1259 # in the correct order, as some types are also other allowed types.
1260 # So basestring must be checked before Iterable
1261 # and bytes/bytearray before Iterable but after basestring!
1262 if isinstance(s, Bits):
1263 if length is None:
1264 length = s.len - offset
1265 self._setbytes_unsafe(s._datastore.rawbytes, length, s._offset + offset)
1266 return
1267 if isinstance(s, file):
1268 if offset is None:
1269 offset = 0
1270 if length is None:
1271 length = os.path.getsize(s.name) * 8 - offset
1272 byteoffset, offset = divmod(offset, 8)
1273 bytelength = (length + byteoffset * 8 + offset + 7) // 8 - byteoffset
1274 m = MmapByteArray(s, bytelength, byteoffset)
1275 if length + byteoffset * 8 + offset > m.filelength * 8:
1276 raise CreationError("File is not long enough for specified "
1277 "length and offset.")
1278 self._datastore = ConstByteStore(m, length, offset)
1279 return
1280 if length is not None:
1281 raise CreationError("The length keyword isn't applicable to this initialiser.")
1282 if offset:
1283 raise CreationError("The offset keyword isn't applicable to this initialiser.")
1284 if isinstance(s, basestring):
1285 bs = self._converttobitstring(s)
1286 assert bs._offset == 0
1287 self._setbytes_unsafe(bs._datastore.rawbytes, bs.length, 0)
1288 return
1289 if isinstance(s, (bytes, bytearray)):
1290 self._setbytes_unsafe(bytearray(s), len(s) * 8, 0)
1291 return
1292 if isinstance(s, array.array):
1293 b = s.tostring()
1294 self._setbytes_unsafe(bytearray(b), len(b) * 8, 0)
1295 return
1296 if isinstance(s, numbers.Integral):
1297 # Initialise with s zero bits.
1298 if s < 0:
1299 msg = "Can't create bitstring of negative length {0}."
1300 raise CreationError(msg, s)
1301 data = bytearray((s + 7) // 8)
1302 self._datastore = ByteStore(data, s, 0)
1303 return
1304 if isinstance(s, collections.abc.Iterable):
1305 # Evaluate each item as True or False and set bits to 1 or 0.
1306 self._setbin_unsafe(''.join(str(int(bool(x))) for x in s))
1307 return
1308 raise TypeError("Cannot initialise bitstring from {0}.".format(type(s)))
1309

◆ _setbin_safe()

_setbin_safe ( self,
binstring )
protectedinherited
Reset the bitstring to the value given in binstring.

Definition at line 1834 of file bitstring.py.

1834 def _setbin_safe(self, binstring):
1835 """Reset the bitstring to the value given in binstring."""
1836 binstring = tidy_input_string(binstring)
1837 # remove any 0b if present
1838 binstring = binstring.replace('0b', '')
1839 self._setbin_unsafe(binstring)
1840

◆ _setbin_unsafe()

_setbin_unsafe ( self,
binstring )
protectedinherited
Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'.

Definition at line 1841 of file bitstring.py.

1841 def _setbin_unsafe(self, binstring):
1842 """Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'."""
1843 length = len(binstring)
1844 # pad with zeros up to byte boundary if needed
1845 boundary = ((length + 7) // 8) * 8
1846 padded_binstring = binstring + '0' * (boundary - length)\
1847 if len(binstring) < boundary else binstring
1848 try:
1849 bytelist = [int(padded_binstring[x:x + 8], 2)
1850 for x in xrange(0, len(padded_binstring), 8)]
1851 except ValueError:
1852 raise CreationError("Invalid character in bin initialiser {0}.", binstring)
1853 self._setbytes_unsafe(bytearray(bytelist), length, 0)
1854

◆ _setbitpos()

_setbitpos ( self,
pos )
protected
Move to absolute position bit in bitstream.

Definition at line 3818 of file bitstring.py.

3818 def _setbitpos(self, pos):
3819 """Move to absolute position bit in bitstream."""
3820 if pos < 0:
3821 raise ValueError("Bit position cannot be negative.")
3822 if pos > self.len:
3823 raise ValueError("Cannot seek past the end of the data.")
3824 self._pos = pos
3825

◆ _setbool()

_setbool ( self,
value )
protectedinherited

Definition at line 1815 of file bitstring.py.

1815 def _setbool(self, value):
1816 # We deliberately don't want to have implicit conversions to bool here.
1817 # If we did then it would be difficult to deal with the 'False' string.
1818 if value in (1, 'True'):
1819 self._setbytes_unsafe(bytearray(b'\x80'), 1, 0)
1820 elif value in (0, 'False'):
1821 self._setbytes_unsafe(bytearray(b'\x00'), 1, 0)
1822 else:
1823 raise CreationError('Cannot initialise boolean with {0}.', value)
1824

◆ _setbytepos()

_setbytepos ( self,
bytepos )
protected
Move to absolute byte-aligned position in stream.

Definition at line 3808 of file bitstring.py.

3808 def _setbytepos(self, bytepos):
3809 """Move to absolute byte-aligned position in stream."""
3810 self._setbitpos(bytepos * 8)
3811

◆ _setbytes_safe()

_setbytes_safe ( self,
data,
length = None,
offset = 0 )
protectedinherited
Set the data from a string.

Definition at line 1325 of file bitstring.py.

1325 def _setbytes_safe(self, data, length=None, offset=0):
1326 """Set the data from a string."""
1327 data = bytearray(data)
1328 if length is None:
1329 # Use to the end of the data
1330 length = len(data) * 8 - offset
1331 self._datastore = ByteStore(data, length, offset)
1332 else:
1333 if length + offset > len(data) * 8:
1334 msg = "Not enough data present. Need {0} bits, have {1}."
1335 raise CreationError(msg, length + offset, len(data) * 8)
1336 if length == 0:
1337 self._datastore = ByteStore(bytearray(0))
1338 else:
1339 self._datastore = ByteStore(data, length, offset)
1340

◆ _setbytes_unsafe()

_setbytes_unsafe ( self,
data,
length,
offset )
protectedinherited
Unchecked version of _setbytes_safe.

Definition at line 1341 of file bitstring.py.

1341 def _setbytes_unsafe(self, data, length, offset):
1342 """Unchecked version of _setbytes_safe."""
1343 self._datastore = ByteStore(data[:], length, offset)
1344 assert self._assertsanity()
1345

◆ _setfile()

_setfile ( self,
filename,
length,
offset )
protectedinherited
Use file as source of bits.

Definition at line 1310 of file bitstring.py.

1310 def _setfile(self, filename, length, offset):
1311 """Use file as source of bits."""
1312 source = open(filename, 'rb')
1313 if offset is None:
1314 offset = 0
1315 if length is None:
1316 length = os.path.getsize(source.name) * 8 - offset
1317 byteoffset, offset = divmod(offset, 8)
1318 bytelength = (length + byteoffset * 8 + offset + 7) // 8 - byteoffset
1319 m = MmapByteArray(source, bytelength, byteoffset)
1320 if length + byteoffset * 8 + offset > m.filelength * 8:
1321 raise CreationError("File is not long enough for specified "
1322 "length and offset.")
1323 self._datastore = ConstByteStore(m, length, offset)
1324

◆ _setfloat()

_setfloat ( self,
f,
length = None )
protectedinherited

Definition at line 1552 of file bitstring.py.

1552 def _setfloat(self, f, length=None):
1553 # If no length given, and we've previously been given a length, use it.
1554 if length is None and hasattr(self, 'len') and self.len != 0:
1555 length = self.len
1556 if length is None or length == 0:
1557 raise CreationError("A non-zero length must be specified with a "
1558 "float initialiser.")
1559 if length == 32:
1560 b = struct.pack('>f', f)
1561 elif length == 64:
1562 b = struct.pack('>d', f)
1563 else:
1564 raise CreationError("floats can only be 32 or 64 bits long, "
1565 "not {0} bits", length)
1566 self._setbytes_unsafe(bytearray(b), length, 0)
1567

◆ _setfloatle()

_setfloatle ( self,
f,
length = None )
protectedinherited

Definition at line 1590 of file bitstring.py.

1590 def _setfloatle(self, f, length=None):
1591 # If no length given, and we've previously been given a length, use it.
1592 if length is None and hasattr(self, 'len') and self.len != 0:
1593 length = self.len
1594 if length is None or length == 0:
1595 raise CreationError("A non-zero length must be specified with a "
1596 "float initialiser.")
1597 if length == 32:
1598 b = struct.pack('<f', f)
1599 elif length == 64:
1600 b = struct.pack('<d', f)
1601 else:
1602 raise CreationError("floats can only be 32 or 64 bits long, "
1603 "not {0} bits", length)
1604 self._setbytes_unsafe(bytearray(b), length, 0)
1605

◆ _sethex()

_sethex ( self,
hexstring )
protectedinherited
Reset the bitstring to have the value given in hexstring.

Definition at line 1910 of file bitstring.py.

1910 def _sethex(self, hexstring):
1911 """Reset the bitstring to have the value given in hexstring."""
1912 hexstring = tidy_input_string(hexstring)
1913 # remove any 0x if present
1914 hexstring = hexstring.replace('0x', '')
1915 length = len(hexstring)
1916 if length % 2:
1917 hexstring += '0'
1918 try:
1919 try:
1920 data = bytearray.fromhex(hexstring)
1921 except TypeError:
1922 # Python 2.6 needs a unicode string (a bug). 2.7 and 3.x work fine.
1923 data = bytearray.fromhex(unicode(hexstring)) # noqa
1924 except ValueError:
1925 raise CreationError("Invalid symbol in hex initialiser.")
1926 self._setbytes_unsafe(data, length * 4, 0)
1927

◆ _setint()

_setint ( self,
int_,
length = None )
protectedinherited
Reset the bitstring to have given signed int interpretation.

Definition at line 1421 of file bitstring.py.

1421 def _setint(self, int_, length=None):
1422 """Reset the bitstring to have given signed int interpretation."""
1423 # If no length given, and we've previously been given a length, use it.
1424 if length is None and hasattr(self, 'len') and self.len != 0:
1425 length = self.len
1426 if length is None or length == 0:
1427 raise CreationError("A non-zero length must be specified with an int initialiser.")
1428 if int_ >= (1 << (length - 1)) or int_ < -(1 << (length - 1)):
1429 raise CreationError("{0} is too large a signed integer for a bitstring of length {1}. "
1430 "The allowed range is [{2}, {3}].", int_, length, -(1 << (length - 1)),
1431 (1 << (length - 1)) - 1)
1432 if int_ >= 0:
1433 self._setuint(int_, length)
1434 return
1435 # TODO: We should decide whether to just use the _setuint, or to do the bit flipping,
1436 # based upon which will be quicker. If the -ive number is less than half the maximum
1437 # possible then it's probably quicker to do the bit flipping...
1438
1439 # Do the 2's complement thing. Add one, set to minus number, then flip bits.
1440 int_ += 1
1441 self._setuint(-int_, length)
1442 self._invert_all()
1443

◆ _setintbe()

_setintbe ( self,
intbe,
length = None )
protectedinherited
Set bitstring to a big-endian signed int interpretation.

Definition at line 1476 of file bitstring.py.

1476 def _setintbe(self, intbe, length=None):
1477 """Set bitstring to a big-endian signed int interpretation."""
1478 if length is not None and length % 8 != 0:
1479 raise CreationError("Big-endian integers must be whole-byte. "
1480 "Length = {0} bits.", length)
1481 self._setint(intbe, length)
1482

◆ _setintle()

_setintle ( self,
intle,
length = None )
protectedinherited

Definition at line 1532 of file bitstring.py.

1532 def _setintle(self, intle, length=None):
1533 if length is not None and length % 8 != 0:
1534 raise CreationError("Little-endian integers must be whole-byte. "
1535 "Length = {0} bits.", length)
1536 self._setint(intle, length)
1537 self._reversebytes(0, self.len)
1538

◆ _setoct()

_setoct ( self,
octstring )
protectedinherited
Reset the bitstring to have the value given in octstring.

Definition at line 1876 of file bitstring.py.

1876 def _setoct(self, octstring):
1877 """Reset the bitstring to have the value given in octstring."""
1878 octstring = tidy_input_string(octstring)
1879 # remove any 0o if present
1880 octstring = octstring.replace('0o', '')
1881 binlist = []
1882 for i in octstring:
1883 try:
1884 if not 0 <= int(i) < 8:
1885 raise ValueError
1886 binlist.append(OCT_TO_BITS[int(i)])
1887 except ValueError:
1888 raise CreationError("Invalid symbol '{0}' in oct initialiser.", i)
1889 self._setbin_unsafe(''.join(binlist))
1890

◆ _setse()

_setse ( self,
i )
protectedinherited
Initialise bitstring with signed exponential-Golomb code for integer i.

Definition at line 1690 of file bitstring.py.

1690 def _setse(self, i):
1691 """Initialise bitstring with signed exponential-Golomb code for integer i."""
1692 if i > 0:
1693 u = (i * 2) - 1
1694 else:
1695 u = -2 * i
1696 self._setue(u)
1697

◆ _setsie()

_setsie ( self,
i )
protectedinherited
Initialise bitstring with signed interleaved exponential-Golomb code for integer i.

Definition at line 1773 of file bitstring.py.

1773 def _setsie(self, i):
1774 """Initialise bitstring with signed interleaved exponential-Golomb code for integer i."""
1775 if not i:
1776 self._setbin_unsafe('1')
1777 else:
1778 self._setuie(abs(i))
1779 self._append(Bits([i < 0]))
1780

◆ _setue()

_setue ( self,
i )
protectedinherited
Initialise bitstring with unsigned exponential-Golomb code for integer i.

Raises CreationError if i < 0.

Definition at line 1629 of file bitstring.py.

1629 def _setue(self, i):
1630 """Initialise bitstring with unsigned exponential-Golomb code for integer i.
1631
1632 Raises CreationError if i < 0.
1633
1634 """
1635 if i < 0:
1636 raise CreationError("Cannot use negative initialiser for unsigned "
1637 "exponential-Golomb.")
1638 if not i:
1639 self._setbin_unsafe('1')
1640 return
1641 tmp = i + 1
1642 leadingzeros = -1
1643 while tmp > 0:
1644 tmp >>= 1
1645 leadingzeros += 1
1646 remainingpart = i + 1 - (1 << leadingzeros)
1647 binstring = '0' * leadingzeros + '1' + Bits(uint=remainingpart,
1648 length=leadingzeros).bin
1649 self._setbin_unsafe(binstring)
1650

◆ _setuie()

_setuie ( self,
i )
protectedinherited
Initialise bitstring with unsigned interleaved exponential-Golomb code for integer i.

Raises CreationError if i < 0.

Definition at line 1728 of file bitstring.py.

1728 def _setuie(self, i):
1729 """Initialise bitstring with unsigned interleaved exponential-Golomb code for integer i.
1730
1731 Raises CreationError if i < 0.
1732
1733 """
1734 if i < 0:
1735 raise CreationError("Cannot use negative initialiser for unsigned "
1736 "interleaved exponential-Golomb.")
1737 self._setbin_unsafe('1' if i == 0 else '0' + '0'.join(bin(i + 1)[3:]) + '1')
1738

◆ _setuint()

_setuint ( self,
uint,
length = None )
protectedinherited
Reset the bitstring to have given unsigned int interpretation.

Definition at line 1362 of file bitstring.py.

1362 def _setuint(self, uint, length=None):
1363 """Reset the bitstring to have given unsigned int interpretation."""
1364 try:
1365 if length is None:
1366 # Use the whole length. Deliberately not using .len here.
1367 length = self._datastore.bitlength
1368 except AttributeError:
1369 # bitstring doesn't have a _datastore as it hasn't been created!
1370 pass
1371 # TODO: All this checking code should be hoisted out of here!
1372 if length is None or length == 0:
1373 raise CreationError("A non-zero length must be specified with a "
1374 "uint initialiser.")
1375 if uint >= (1 << length):
1376 msg = "{0} is too large an unsigned integer for a bitstring of length {1}. "\
1377 "The allowed range is [0, {2}]."
1378 raise CreationError(msg, uint, length, (1 << length) - 1)
1379 if uint < 0:
1380 raise CreationError("uint cannot be initialised by a negative number.")
1381 s = hex(uint)[2:]
1382 s = s.rstrip('L')
1383 if len(s) & 1:
1384 s = '0' + s
1385 try:
1386 data = bytes.fromhex(s)
1387 except AttributeError:
1388 # the Python 2.x way
1389 data = binascii.unhexlify(s)
1390 # Now add bytes as needed to get the right length.
1391 extrabytes = ((length + 7) // 8) - len(data)
1392 if extrabytes > 0:
1393 data = b'\x00' * extrabytes + data
1394 offset = 8 - (length % 8)
1395 if offset == 8:
1396 offset = 0
1397 self._setbytes_unsafe(bytearray(data), length, offset)
1398

◆ _setuintbe()

_setuintbe ( self,
uintbe,
length = None )
protectedinherited
Set the bitstring to a big-endian unsigned int interpretation.

Definition at line 1458 of file bitstring.py.

1458 def _setuintbe(self, uintbe, length=None):
1459 """Set the bitstring to a big-endian unsigned int interpretation."""
1460 if length is not None and length % 8 != 0:
1461 raise CreationError("Big-endian integers must be whole-byte. "
1462 "Length = {0} bits.", length)
1463 self._setuint(uintbe, length)
1464

◆ _setuintle()

_setuintle ( self,
uintle,
length = None )
protectedinherited

Definition at line 1494 of file bitstring.py.

1494 def _setuintle(self, uintle, length=None):
1495 if length is not None and length % 8 != 0:
1496 raise CreationError("Little-endian integers must be whole-byte. "
1497 "Length = {0} bits.", length)
1498 self._setuint(uintle, length)
1499 self._reversebytes(0, self.len)
1500

◆ _slice()

_slice ( self,
start,
end )
protectedinherited
Used internally to get a slice, without error checking.

Definition at line 2008 of file bitstring.py.

2008 def _slice(self, start, end):
2009 """Used internally to get a slice, without error checking."""
2010 if end == start:
2011 return self.__class__()
2012 offset = self._offset
2013 startbyte, newoffset = divmod(start + offset, 8)
2014 endbyte = (end + offset - 1) // 8
2015 bs = self.__class__()
2016 bs._setbytes_unsafe(self._datastore.getbyteslice(startbyte, endbyte + 1), end - start, newoffset)
2017 return bs
2018

◆ _truncateend()

_truncateend ( self,
bits )
protectedinherited
Truncate bits from the end of the bitstring.

Definition at line 2068 of file bitstring.py.

2068 def _truncateend(self, bits):
2069 """Truncate bits from the end of the bitstring."""
2070 assert 0 <= bits <= self.len
2071 if not bits:
2072 return
2073 if bits == self.len:
2074 self._clear()
2075 return
2076 newlength_in_bytes = (self._offset + self.len - bits + 7) // 8
2077 self._setbytes_unsafe(self._datastore.getbyteslice(0, newlength_in_bytes), self.len - bits,
2078 self._offset)
2079 assert self._assertsanity()
2080

◆ _truncatestart()

_truncatestart ( self,
bits )
protectedinherited
Truncate bits from the start of the bitstring.

Definition at line 2055 of file bitstring.py.

2055 def _truncatestart(self, bits):
2056 """Truncate bits from the start of the bitstring."""
2057 assert 0 <= bits <= self.len
2058 if not bits:
2059 return
2060 if bits == self.len:
2061 self._clear()
2062 return
2063 bytepos, offset = divmod(self._offset + bits, 8)
2064 self._setbytes_unsafe(self._datastore.getbyteslice(bytepos, self._datastore.bytelength), self.len - bits,
2065 offset)
2066 assert self._assertsanity()
2067

◆ _unset()

_unset ( self,
pos )
protectedinherited
Set bit at pos to 0.

Definition at line 2179 of file bitstring.py.

2179 def _unset(self, pos):
2180 """Set bit at pos to 0."""
2181 assert 0 <= pos < self.len
2182 self._datastore.unsetbit(pos)
2183

◆ _validate_slice()

_validate_slice ( self,
start,
end )
protectedinherited
Validate start and end and return them as positive bit positions.

Definition at line 2253 of file bitstring.py.

2253 def _validate_slice(self, start, end):
2254 """Validate start and end and return them as positive bit positions."""
2255 if start is None:
2256 start = 0
2257 elif start < 0:
2258 start += self.len
2259 if end is None:
2260 end = self.len
2261 elif end < 0:
2262 end += self.len
2263 if not 0 <= end <= self.len:
2264 raise ValueError("end is not a valid position in the bitstring.")
2265 if not 0 <= start <= self.len:
2266 raise ValueError("start is not a valid position in the bitstring.")
2267 if end < start:
2268 raise ValueError("end must not be less than start.")
2269 return start, end
2270

◆ all()

all ( self,
value,
pos = None )
inherited
Return True if one or many bits are all set to value.

value -- If value is True then checks for bits set to 1, otherwise
         checks for bits set to 0.
pos -- An iterable of bit positions. Negative numbers are treated in
       the same way as slice indices. Defaults to the whole bitstring.

Definition at line 2732 of file bitstring.py.

2732 def all(self, value, pos=None):
2733 """Return True if one or many bits are all set to value.
2734
2735 value -- If value is True then checks for bits set to 1, otherwise
2736 checks for bits set to 0.
2737 pos -- An iterable of bit positions. Negative numbers are treated in
2738 the same way as slice indices. Defaults to the whole bitstring.
2739
2740 """
2741 value = bool(value)
2742 length = self.len
2743 if pos is None:
2744 pos = xrange(self.len)
2745 for p in pos:
2746 if p < 0:
2747 p += length
2748 if not 0 <= p < length:
2749 raise IndexError("Bit position {0} out of range.".format(p))
2750 if not self._datastore.getbit(p) is value:
2751 return False
2752 return True
2753

◆ any()

any ( self,
value,
pos = None )
inherited
Return True if any of one or many bits are set to value.

value -- If value is True then checks for bits set to 1, otherwise
         checks for bits set to 0.
pos -- An iterable of bit positions. Negative numbers are treated in
       the same way as slice indices. Defaults to the whole bitstring.

Definition at line 2754 of file bitstring.py.

2754 def any(self, value, pos=None):
2755 """Return True if any of one or many bits are set to value.
2756
2757 value -- If value is True then checks for bits set to 1, otherwise
2758 checks for bits set to 0.
2759 pos -- An iterable of bit positions. Negative numbers are treated in
2760 the same way as slice indices. Defaults to the whole bitstring.
2761
2762 """
2763 value = bool(value)
2764 length = self.len
2765 if pos is None:
2766 pos = xrange(self.len)
2767 for p in pos:
2768 if p < 0:
2769 p += length
2770 if not 0 <= p < length:
2771 raise IndexError("Bit position {0} out of range.".format(p))
2772 if self._datastore.getbit(p) is value:
2773 return True
2774 return False
2775

◆ bytealign()

bytealign ( self)
Align to next byte and return number of skipped bits.

Raises ValueError if the end of the bitstring is reached before
aligning to the next byte.

Definition at line 3997 of file bitstring.py.

3997 def bytealign(self):
3998 """Align to next byte and return number of skipped bits.
3999
4000 Raises ValueError if the end of the bitstring is reached before
4001 aligning to the next byte.
4002
4003 """
4004 skipped = (8 - (self._pos % 8)) % 8
4005 self.pos += self._offset + skipped
4006 assert self._assertsanity()
4007 return skipped
4008

◆ count()

count ( self,
value )
inherited
Return count of total number of either zero or one bits.

value -- If True then bits set to 1 are counted, otherwise bits set
         to 0 are counted.

>>> Bits('0xef').count(1)
7

Definition at line 2776 of file bitstring.py.

2776 def count(self, value):
2777 """Return count of total number of either zero or one bits.
2778
2779 value -- If True then bits set to 1 are counted, otherwise bits set
2780 to 0 are counted.
2781
2782 >>> Bits('0xef').count(1)
2783 7
2784
2785 """
2786 if not self.len:
2787 return 0
2788 # count the number of 1s (from which it's easy to work out the 0s).
2789 # Don't count the final byte yet.
2790 count = sum(BIT_COUNT[self._datastore.getbyte(i)] for i in xrange(self._datastore.bytelength - 1))
2791 # adjust for bits at start that aren't part of the bitstring
2792 if self._offset:
2793 count -= BIT_COUNT[self._datastore.getbyte(0) >> (8 - self._offset)]
2794 # and count the last 1 - 8 bits at the end.
2795 endbits = self._datastore.bytelength * 8 - (self._offset + self.len)
2796 count += BIT_COUNT[self._datastore.getbyte(self._datastore.bytelength - 1) >> endbits]
2797 return count if value else self.len - count
2798

◆ cut()

cut ( self,
bits,
start = None,
end = None,
count = None )
inherited
Return bitstring generator by cutting into bits sized chunks.

bits -- The size in bits of the bitstring chunks to generate.
start -- The bit position to start the first cut. Defaults to 0.
end -- The bit position one past the last bit to use in the cut.
       Defaults to self.len.
count -- If specified then at most count items are generated.
         Default is to cut as many times as possible.

Definition at line 2553 of file bitstring.py.

2553 def cut(self, bits, start=None, end=None, count=None):
2554 """Return bitstring generator by cutting into bits sized chunks.
2555
2556 bits -- The size in bits of the bitstring chunks to generate.
2557 start -- The bit position to start the first cut. Defaults to 0.
2558 end -- The bit position one past the last bit to use in the cut.
2559 Defaults to self.len.
2560 count -- If specified then at most count items are generated.
2561 Default is to cut as many times as possible.
2562
2563 """
2564 start, end = self._validate_slice(start, end)
2565 if count is not None and count < 0:
2566 raise ValueError("Cannot cut - count must be >= 0.")
2567 if bits <= 0:
2568 raise ValueError("Cannot cut - bits must be >= 0.")
2569 c = 0
2570 while count is None or c < count:
2571 c += 1
2572 nextchunk = self._slice(start, min(start + bits, end))
2573 if nextchunk.len != bits:
2574 return
2575 assert nextchunk._assertsanity()
2576 yield nextchunk
2577 start += bits
2578 return
2579

◆ endswith()

endswith ( self,
suffix,
start = None,
end = None )
inherited
Return whether the current bitstring ends with suffix.

suffix -- The bitstring to search for.
start -- The bit position to start from. Defaults to 0.
end -- The bit position to end at. Defaults to self.len.

Definition at line 2717 of file bitstring.py.

2717 def endswith(self, suffix, start=None, end=None):
2718 """Return whether the current bitstring ends with suffix.
2719
2720 suffix -- The bitstring to search for.
2721 start -- The bit position to start from. Defaults to 0.
2722 end -- The bit position to end at. Defaults to self.len.
2723
2724 """
2725 suffix = Bits(suffix)
2726 start, end = self._validate_slice(start, end)
2727 if start + suffix.len > end:
2728 return False
2729 start = end - suffix.len
2730 return self._slice(start, end) == suffix
2731

◆ find()

find ( self,
bs,
start = None,
end = None,
bytealigned = None )
inherited
Find first occurrence of substring bs.

Returns a single item tuple with the bit position if found, or an
empty tuple if not found. The bit position (pos property) will
also be set to the start of the substring if it is found.

bs -- The bitstring to find.
start -- The bit position to start the search. Defaults to 0.
end -- The bit position one past the last bit to search.
       Defaults to self.len.
bytealigned -- If True the bitstring will only be
               found on byte boundaries.

Raises ValueError if bs is empty, if start < 0, if end > self.len or
if end < start.

>>> BitArray('0xc3e').find('0b1111')
(6,)

Definition at line 2424 of file bitstring.py.

2424 def find(self, bs, start=None, end=None, bytealigned=None):
2425 """Find first occurrence of substring bs.
2426
2427 Returns a single item tuple with the bit position if found, or an
2428 empty tuple if not found. The bit position (pos property) will
2429 also be set to the start of the substring if it is found.
2430
2431 bs -- The bitstring to find.
2432 start -- The bit position to start the search. Defaults to 0.
2433 end -- The bit position one past the last bit to search.
2434 Defaults to self.len.
2435 bytealigned -- If True the bitstring will only be
2436 found on byte boundaries.
2437
2438 Raises ValueError if bs is empty, if start < 0, if end > self.len or
2439 if end < start.
2440
2441 >>> BitArray('0xc3e').find('0b1111')
2442 (6,)
2443
2444 """
2445 bs = Bits(bs)
2446 if not bs.len:
2447 raise ValueError("Cannot find an empty bitstring.")
2448 start, end = self._validate_slice(start, end)
2449 if bytealigned is None:
2450 bytealigned = globals()['bytealigned']
2451 if bytealigned and not bs.len % 8 and not self._datastore.offset:
2452 p = self._findbytes(bs.bytes, start, end, bytealigned)
2453 else:
2454 p = self._findregex(re.compile(bs._getbin()), start, end, bytealigned)
2455 # If called from a class that has a pos, set it
2456 try:
2457 self._pos = p[0]
2458 except (AttributeError, IndexError):
2459 pass
2460 return p
2461

◆ findall()

findall ( self,
bs,
start = None,
end = None,
count = None,
bytealigned = None )
inherited
Find all occurrences of bs. Return generator of bit positions.

bs -- The bitstring to find.
start -- The bit position to start the search. Defaults to 0.
end -- The bit position one past the last bit to search.
       Defaults to self.len.
count -- The maximum number of occurrences to find.
bytealigned -- If True the bitstring will only be found on
               byte boundaries.

Raises ValueError if bs is empty, if start < 0, if end > self.len or
if end < start.

Note that all occurrences of bs are found, even if they overlap.

Definition at line 2462 of file bitstring.py.

2462 def findall(self, bs, start=None, end=None, count=None, bytealigned=None):
2463 """Find all occurrences of bs. Return generator of bit positions.
2464
2465 bs -- The bitstring to find.
2466 start -- The bit position to start the search. Defaults to 0.
2467 end -- The bit position one past the last bit to search.
2468 Defaults to self.len.
2469 count -- The maximum number of occurrences to find.
2470 bytealigned -- If True the bitstring will only be found on
2471 byte boundaries.
2472
2473 Raises ValueError if bs is empty, if start < 0, if end > self.len or
2474 if end < start.
2475
2476 Note that all occurrences of bs are found, even if they overlap.
2477
2478 """
2479 if count is not None and count < 0:
2480 raise ValueError("In findall, count must be >= 0.")
2481 bs = Bits(bs)
2482 start, end = self._validate_slice(start, end)
2483 if bytealigned is None:
2484 bytealigned = globals()['bytealigned']
2485 c = 0
2486 if bytealigned and not bs.len % 8 and not self._datastore.offset:
2487 # Use the quick find method
2488 f = self._findbytes
2489 x = bs._getbytes()
2490 else:
2491 f = self._findregex
2492 x = re.compile(bs._getbin())
2493 while True:
2494
2495 p = f(x, start, end, bytealigned)
2496 if not p:
2497 break
2498 if count is not None and c >= count:
2499 return
2500 c += 1
2501 try:
2502 self._pos = p[0]
2503 except AttributeError:
2504 pass
2505 yield p[0]
2506 if bytealigned:
2507 start = p[0] + 8
2508 else:
2509 start = p[0] + 1
2510 if start >= end:
2511 break
2512 return
2513

◆ join()

join ( self,
sequence )
inherited
Return concatenation of bitstrings joined by self.

sequence -- A sequence of bitstrings.

Definition at line 2637 of file bitstring.py.

2637 def join(self, sequence):
2638 """Return concatenation of bitstrings joined by self.
2639
2640 sequence -- A sequence of bitstrings.
2641
2642 """
2643 s = self.__class__()
2644 i = iter(sequence)
2645 try:
2646 s._append(Bits(next(i)))
2647 while True:
2648 n = next(i)
2649 s._append(self)
2650 s._append(Bits(n))
2651 except StopIteration:
2652 pass
2653 return s
2654

◆ peek()

peek ( self,
fmt )
Interpret next bits according to format string and return result.

fmt -- Token string describing how to interpret the next bits.

The position in the bitstring is not changed. If not enough bits are
available then all bits to the end of the bitstring will be used.

Raises ReadError if not enough bits are available.
Raises ValueError if the format is not understood.

See the docstring for 'read' for token examples.

Definition at line 3956 of file bitstring.py.

3956 def peek(self, fmt):
3957 """Interpret next bits according to format string and return result.
3958
3959 fmt -- Token string describing how to interpret the next bits.
3960
3961 The position in the bitstring is not changed. If not enough bits are
3962 available then all bits to the end of the bitstring will be used.
3963
3964 Raises ReadError if not enough bits are available.
3965 Raises ValueError if the format is not understood.
3966
3967 See the docstring for 'read' for token examples.
3968
3969 """
3970 pos_before = self._pos
3971 value = self.read(fmt)
3972 self._pos = pos_before
3973 return value
3974

◆ peeklist()

peeklist ( self,
fmt,
** kwargs )
Interpret next bits according to format string(s) and return list.

fmt -- One or more strings with comma separated tokens describing
       how to interpret the next bits in the bitstring.
kwargs -- A dictionary or keyword-value pairs - the keywords used in the
          format string will be replaced with their given value.

The position in the bitstring is not changed. If not enough bits are
available then all bits to the end of the bitstring will be used.

Raises ReadError if not enough bits are available.
Raises ValueError if the format is not understood.

See the docstring for 'read' for token examples.

Definition at line 3975 of file bitstring.py.

3975 def peeklist(self, fmt, **kwargs):
3976 """Interpret next bits according to format string(s) and return list.
3977
3978 fmt -- One or more strings with comma separated tokens describing
3979 how to interpret the next bits in the bitstring.
3980 kwargs -- A dictionary or keyword-value pairs - the keywords used in the
3981 format string will be replaced with their given value.
3982
3983 The position in the bitstring is not changed. If not enough bits are
3984 available then all bits to the end of the bitstring will be used.
3985
3986 Raises ReadError if not enough bits are available.
3987 Raises ValueError if the format is not understood.
3988
3989 See the docstring for 'read' for token examples.
3990
3991 """
3992 pos = self._pos
3993 return_values = self.readlist(fmt, **kwargs)
3994 self._pos = pos
3995 return return_values
3996

◆ read()

read ( self,
fmt )
Interpret next bits according to the format string and return result.

fmt -- Token string describing how to interpret the next bits.

Token examples: 'int:12'    : 12 bits as a signed integer
                'uint:8'    : 8 bits as an unsigned integer
                'float:64'  : 8 bytes as a big-endian float
                'intbe:16'  : 2 bytes as a big-endian signed integer
                'uintbe:16' : 2 bytes as a big-endian unsigned integer
                'intle:32'  : 4 bytes as a little-endian signed integer
                'uintle:32' : 4 bytes as a little-endian unsigned integer
                'floatle:64': 8 bytes as a little-endian float
                'intne:24'  : 3 bytes as a native-endian signed integer
                'uintne:24' : 3 bytes as a native-endian unsigned integer
                'floatne:32': 4 bytes as a native-endian float
                'hex:80'    : 80 bits as a hex string
                'oct:9'     : 9 bits as an octal string
                'bin:1'     : single bit binary string
                'ue'        : next bits as unsigned exp-Golomb code
                'se'        : next bits as signed exp-Golomb code
                'uie'       : next bits as unsigned interleaved exp-Golomb code
                'sie'       : next bits as signed interleaved exp-Golomb code
                'bits:5'    : 5 bits as a bitstring
                'bytes:10'  : 10 bytes as a bytes object
                'bool'      : 1 bit as a bool
                'pad:3'     : 3 bits of padding to ignore - returns None

fmt may also be an integer, which will be treated like the 'bits' token.

The position in the bitstring is advanced to after the read items.

Raises ReadError if not enough bits are available.
Raises ValueError if the format is not understood.

Definition at line 3854 of file bitstring.py.

3854 def read(self, fmt):
3855 """Interpret next bits according to the format string and return result.
3856
3857 fmt -- Token string describing how to interpret the next bits.
3858
3859 Token examples: 'int:12' : 12 bits as a signed integer
3860 'uint:8' : 8 bits as an unsigned integer
3861 'float:64' : 8 bytes as a big-endian float
3862 'intbe:16' : 2 bytes as a big-endian signed integer
3863 'uintbe:16' : 2 bytes as a big-endian unsigned integer
3864 'intle:32' : 4 bytes as a little-endian signed integer
3865 'uintle:32' : 4 bytes as a little-endian unsigned integer
3866 'floatle:64': 8 bytes as a little-endian float
3867 'intne:24' : 3 bytes as a native-endian signed integer
3868 'uintne:24' : 3 bytes as a native-endian unsigned integer
3869 'floatne:32': 4 bytes as a native-endian float
3870 'hex:80' : 80 bits as a hex string
3871 'oct:9' : 9 bits as an octal string
3872 'bin:1' : single bit binary string
3873 'ue' : next bits as unsigned exp-Golomb code
3874 'se' : next bits as signed exp-Golomb code
3875 'uie' : next bits as unsigned interleaved exp-Golomb code
3876 'sie' : next bits as signed interleaved exp-Golomb code
3877 'bits:5' : 5 bits as a bitstring
3878 'bytes:10' : 10 bytes as a bytes object
3879 'bool' : 1 bit as a bool
3880 'pad:3' : 3 bits of padding to ignore - returns None
3881
3882 fmt may also be an integer, which will be treated like the 'bits' token.
3883
3884 The position in the bitstring is advanced to after the read items.
3885
3886 Raises ReadError if not enough bits are available.
3887 Raises ValueError if the format is not understood.
3888
3889 """
3890 if isinstance(fmt, numbers.Integral):
3891 if fmt < 0:
3892 raise ValueError("Cannot read negative amount.")
3893 if fmt > self.len - self._pos:
3894 raise ReadError("Cannot read {0} bits, only {1} available.",
3895 fmt, self.len - self._pos)
3896 bs = self._slice(self._pos, self._pos + fmt)
3897 self._pos += fmt
3898 return bs
3899 p = self._pos
3900 _, token = tokenparser(fmt)
3901 if len(token) != 1:
3902 self._pos = p
3903 raise ValueError("Format string should be a single token, not {0} "
3904 "tokens - use readlist() instead.".format(len(token)))
3905 name, length, _ = token[0]
3906 if length is None:
3907 length = self.len - self._pos
3908 value, self._pos = self._readtoken(name, self._pos, length)
3909 return value
3910

◆ readlist()

readlist ( self,
fmt,
** kwargs )
Interpret next bits according to format string(s) and return list.

fmt -- A single string or list of strings with comma separated tokens
       describing how to interpret the next bits in the bitstring. Items
       can also be integers, for reading new bitstring of the given length.
kwargs -- A dictionary or keyword-value pairs - the keywords used in the
          format string will be replaced with their given value.

The position in the bitstring is advanced to after the read items.

Raises ReadError is not enough bits are available.
Raises ValueError if the format is not understood.

See the docstring for 'read' for token examples. 'pad' tokens are skipped
and not added to the returned list.

>>> h, b1, b2 = s.readlist('hex:20, bin:5, bin:3')
>>> i, bs1, bs2 = s.readlist(['uint:12', 10, 10])

Definition at line 3911 of file bitstring.py.

3911 def readlist(self, fmt, **kwargs):
3912 """Interpret next bits according to format string(s) and return list.
3913
3914 fmt -- A single string or list of strings with comma separated tokens
3915 describing how to interpret the next bits in the bitstring. Items
3916 can also be integers, for reading new bitstring of the given length.
3917 kwargs -- A dictionary or keyword-value pairs - the keywords used in the
3918 format string will be replaced with their given value.
3919
3920 The position in the bitstring is advanced to after the read items.
3921
3922 Raises ReadError is not enough bits are available.
3923 Raises ValueError if the format is not understood.
3924
3925 See the docstring for 'read' for token examples. 'pad' tokens are skipped
3926 and not added to the returned list.
3927
3928 >>> h, b1, b2 = s.readlist('hex:20, bin:5, bin:3')
3929 >>> i, bs1, bs2 = s.readlist(['uint:12', 10, 10])
3930
3931 """
3932 value, self._pos = self._readlist(fmt, self._pos, **kwargs)
3933 return value
3934

◆ readto()

readto ( self,
bs,
bytealigned = None )
Read up to and including next occurrence of bs and return result.

bs -- The bitstring to find. An integer is not permitted.
bytealigned -- If True the bitstring will only be
               found on byte boundaries.

Raises ValueError if bs is empty.
Raises ReadError if bs is not found.

Definition at line 3935 of file bitstring.py.

3935 def readto(self, bs, bytealigned=None):
3936 """Read up to and including next occurrence of bs and return result.
3937
3938 bs -- The bitstring to find. An integer is not permitted.
3939 bytealigned -- If True the bitstring will only be
3940 found on byte boundaries.
3941
3942 Raises ValueError if bs is empty.
3943 Raises ReadError if bs is not found.
3944
3945 """
3946 if isinstance(bs, numbers.Integral):
3947 raise ValueError("Integers cannot be searched for")
3948 bs = Bits(bs)
3949 oldpos = self._pos
3950 p = self.find(bs, self._pos, bytealigned=bytealigned)
3951 if not p:
3952 raise ReadError("Substring not found")
3953 self._pos += bs.len
3954 return self._slice(oldpos, self._pos)
3955

◆ rfind()

rfind ( self,
bs,
start = None,
end = None,
bytealigned = None )
inherited
Find final occurrence of substring bs.

Returns a single item tuple with the bit position if found, or an
empty tuple if not found. The bit position (pos property) will
also be set to the start of the substring if it is found.

bs -- The bitstring to find.
start -- The bit position to end the reverse search. Defaults to 0.
end -- The bit position one past the first bit to reverse search.
       Defaults to self.len.
bytealigned -- If True the bitstring will only be found on byte
               boundaries.

Raises ValueError if bs is empty, if start < 0, if end > self.len or
if end < start.

Definition at line 2514 of file bitstring.py.

2514 def rfind(self, bs, start=None, end=None, bytealigned=None):
2515 """Find final occurrence of substring bs.
2516
2517 Returns a single item tuple with the bit position if found, or an
2518 empty tuple if not found. The bit position (pos property) will
2519 also be set to the start of the substring if it is found.
2520
2521 bs -- The bitstring to find.
2522 start -- The bit position to end the reverse search. Defaults to 0.
2523 end -- The bit position one past the first bit to reverse search.
2524 Defaults to self.len.
2525 bytealigned -- If True the bitstring will only be found on byte
2526 boundaries.
2527
2528 Raises ValueError if bs is empty, if start < 0, if end > self.len or
2529 if end < start.
2530
2531 """
2532 bs = Bits(bs)
2533 start, end = self._validate_slice(start, end)
2534 if bytealigned is None:
2535 bytealigned = globals()['bytealigned']
2536 if not bs.len:
2537 raise ValueError("Cannot find an empty bitstring.")
2538 # Search chunks starting near the end and then moving back
2539 # until we find bs.
2540 increment = max(8192, bs.len * 80)
2541 buffersize = min(increment + bs.len, end - start)
2542 pos = max(start, end - buffersize)
2543 while True:
2544 found = list(self.findall(bs, start=pos, end=pos + buffersize,
2545 bytealigned=bytealigned))
2546 if not found:
2547 if pos == start:
2548 return ()
2549 pos = max(start, pos - increment)
2550 continue
2551 return (found[-1],)
2552

◆ split()

split ( self,
delimiter,
start = None,
end = None,
count = None,
bytealigned = None )
inherited
Return bitstring generator by splittling using a delimiter.

The first item returned is the initial bitstring before the delimiter,
which may be an empty bitstring.

delimiter -- The bitstring used as the divider.
start -- The bit position to start the split. Defaults to 0.
end -- The bit position one past the last bit to use in the split.
       Defaults to self.len.
count -- If specified then at most count items are generated.
         Default is to split as many times as possible.
bytealigned -- If True splits will only occur on byte boundaries.

Raises ValueError if the delimiter is empty.

Definition at line 2580 of file bitstring.py.

2581 bytealigned=None):
2582 """Return bitstring generator by splittling using a delimiter.
2583
2584 The first item returned is the initial bitstring before the delimiter,
2585 which may be an empty bitstring.
2586
2587 delimiter -- The bitstring used as the divider.
2588 start -- The bit position to start the split. Defaults to 0.
2589 end -- The bit position one past the last bit to use in the split.
2590 Defaults to self.len.
2591 count -- If specified then at most count items are generated.
2592 Default is to split as many times as possible.
2593 bytealigned -- If True splits will only occur on byte boundaries.
2594
2595 Raises ValueError if the delimiter is empty.
2596
2597 """
2598 delimiter = Bits(delimiter)
2599 if not delimiter.len:
2600 raise ValueError("split delimiter cannot be empty.")
2601 start, end = self._validate_slice(start, end)
2602 if bytealigned is None:
2603 bytealigned = globals()['bytealigned']
2604 if count is not None and count < 0:
2605 raise ValueError("Cannot split - count must be >= 0.")
2606 if count == 0:
2607 return
2608 if bytealigned and not delimiter.len % 8 and not self._datastore.offset:
2609 # Use the quick find method
2610 f = self._findbytes
2611 x = delimiter._getbytes()
2612 else:
2613 f = self._findregex
2614 x = re.compile(delimiter._getbin())
2615 found = f(x, start, end, bytealigned)
2616 if not found:
2617 # Initial bits are the whole bitstring being searched
2618 yield self._slice(start, end)
2619 return
2620 # yield the bytes before the first occurrence of the delimiter, even if empty
2621 yield self._slice(start, found[0])
2622 startpos = pos = found[0]
2623 c = 1
2624 while count is None or c < count:
2625 pos += delimiter.len
2626 found = f(x, pos, end, bytealigned)
2627 if not found:
2628 # No more occurrences, so return the rest of the bitstring
2629 yield self._slice(startpos, end)
2630 return
2631 c += 1
2632 yield self._slice(startpos, found[0])
2633 startpos = pos = found[0]
2634 # Have generated count bitstrings, so time to quit.
2635 return
2636

◆ startswith()

startswith ( self,
prefix,
start = None,
end = None )
inherited
Return whether the current bitstring starts with prefix.

prefix -- The bitstring to search for.
start -- The bit position to start from. Defaults to 0.
end -- The bit position to end at. Defaults to self.len.

Definition at line 2702 of file bitstring.py.

2702 def startswith(self, prefix, start=None, end=None):
2703 """Return whether the current bitstring starts with prefix.
2704
2705 prefix -- The bitstring to search for.
2706 start -- The bit position to start from. Defaults to 0.
2707 end -- The bit position to end at. Defaults to self.len.
2708
2709 """
2710 prefix = Bits(prefix)
2711 start, end = self._validate_slice(start, end)
2712 if end < start + prefix.len:
2713 return False
2714 end = start + prefix.len
2715 return self._slice(start, end) == prefix
2716

◆ tobytes()

tobytes ( self)
inherited
Return the bitstring as bytes, padding with zero bits if needed.

Up to seven zero bits will be added at the end to byte align.

Definition at line 2655 of file bitstring.py.

2655 def tobytes(self):
2656 """Return the bitstring as bytes, padding with zero bits if needed.
2657
2658 Up to seven zero bits will be added at the end to byte align.
2659
2660 """
2661 d = offsetcopy(self._datastore, 0).rawbytes
2662 # Need to ensure that unused bits at end are set to zero
2663 unusedbits = 8 - self.len % 8
2664 if unusedbits != 8:
2665 d[-1] &= (0xff << unusedbits)
2666 return bytes(d)
2667

◆ tofile()

tofile ( self,
f )
inherited
Write the bitstring to a file object, padding with zero bits if needed.

Up to seven zero bits will be added at the end to byte align.

Definition at line 2668 of file bitstring.py.

2668 def tofile(self, f):
2669 """Write the bitstring to a file object, padding with zero bits if needed.
2670
2671 Up to seven zero bits will be added at the end to byte align.
2672
2673 """
2674 # If the bitstring is file based then we don't want to read it all
2675 # in to memory.
2676 chunksize = 1024 * 1024 # 1 MB chunks
2677 if not self._offset:
2678 a = 0
2679 bytelen = self._datastore.bytelength
2680 p = self._datastore.getbyteslice(a, min(a + chunksize, bytelen - 1))
2681 while len(p) == chunksize:
2682 f.write(p)
2683 a += chunksize
2684 p = self._datastore.getbyteslice(a, min(a + chunksize, bytelen - 1))
2685 f.write(p)
2686 # Now the final byte, ensuring that unused bits at end are set to 0.
2687 bits_in_final_byte = self.len % 8
2688 if not bits_in_final_byte:
2689 bits_in_final_byte = 8
2690 f.write(self[-bits_in_final_byte:].tobytes())
2691 else:
2692 # Really quite inefficient...
2693 a = 0
2694 b = a + chunksize * 8
2695 while b <= self.len:
2696 f.write(self._slice(a, b)._getbytes())
2697 a += chunksize * 8
2698 b += chunksize * 8
2699 if a != self.len:
2700 f.write(self._slice(a, self.len).tobytes())
2701

◆ unpack()

unpack ( self,
fmt,
** kwargs )
inherited
Interpret the whole bitstring using fmt and return list.

fmt -- A single string or a list of strings with comma separated tokens
       describing how to interpret the bits in the bitstring. Items
       can also be integers, for reading new bitstring of the given length.
kwargs -- A dictionary or keyword-value pairs - the keywords used in the
          format string will be replaced with their given value.

Raises ValueError if the format is not understood. If not enough bits
are available then all bits to the end of the bitstring will be used.

See the docstring for 'read' for token examples.

Definition at line 2271 of file bitstring.py.

2271 def unpack(self, fmt, **kwargs):
2272 """Interpret the whole bitstring using fmt and return list.
2273
2274 fmt -- A single string or a list of strings with comma separated tokens
2275 describing how to interpret the bits in the bitstring. Items
2276 can also be integers, for reading new bitstring of the given length.
2277 kwargs -- A dictionary or keyword-value pairs - the keywords used in the
2278 format string will be replaced with their given value.
2279
2280 Raises ValueError if the format is not understood. If not enough bits
2281 are available then all bits to the end of the bitstring will be used.
2282
2283 See the docstring for 'read' for token examples.
2284
2285 """
2286 return self._readlist(fmt, 0, **kwargs)[0]
2287

Member Data Documentation

◆ __bool__

__bool__ = __nonzero__
staticprivateinherited

Definition at line 1204 of file bitstring.py.

◆ __slots__

tuple __slots__ = ('_pos')
staticprivate

Definition at line 3762 of file bitstring.py.

◆ _datastore

_datastore
protectedinherited

Definition at line 1001 of file bitstring.py.

◆ _getfloatne

_getfloatne = _getfloatle
staticprotectedinherited

Definition at line 2803 of file bitstring.py.

◆ _getintne

_getintne = _getintle
staticprotectedinherited

Definition at line 2809 of file bitstring.py.

◆ _getuintne

_getuintne = _getuintle
staticprotectedinherited

Definition at line 2806 of file bitstring.py.

◆ _pos

_pos = pos
protectedinherited

Definition at line 1170 of file bitstring.py.

◆ _readfloatne

_readfloatne = _readfloatle
staticprotectedinherited

Definition at line 2802 of file bitstring.py.

◆ _readintne

_readintne = _readintle
staticprotectedinherited

Definition at line 2808 of file bitstring.py.

◆ _readuintne

_readuintne = _readuintle
staticprotectedinherited

Definition at line 2805 of file bitstring.py.

◆ _setfloatne

_setfloatne = _setfloatle
staticprotectedinherited

Definition at line 2801 of file bitstring.py.

◆ _setintne

_setintne = _setintle
staticprotectedinherited

Definition at line 2807 of file bitstring.py.

◆ _setuintne

_setuintne = _setuintle
staticprotectedinherited

Definition at line 2804 of file bitstring.py.

Property Documentation

◆ _offset

_offset = property(_getoffset)
staticprotectedinherited

Definition at line 2821 of file bitstring.py.

◆ bin

bin
staticinherited
Initial value:
= property(_getbin,
doc=)

Definition at line 2835 of file bitstring.py.

◆ bitpos

bitpos
static
Initial value:
= property(_getbitpos, _setbitpos,
doc=)

Definition at line 4012 of file bitstring.py.

◆ bool

bool
staticinherited
Initial value:
= property(_getbool,
doc=)

Definition at line 2829 of file bitstring.py.

◆ bytepos

bytepos
static
Initial value:
= property(_getbytepos, _setbytepos,
doc=)

Definition at line 4015 of file bitstring.py.

◆ bytes

bytes
staticinherited
Initial value:
= property(_getbytes,
doc=)

Definition at line 2841 of file bitstring.py.

◆ float

float
staticinherited
Initial value:
= property(_getfloat,
doc=)

Definition at line 2850 of file bitstring.py.

◆ floatbe

floatbe
staticinherited
Initial value:
= property(_getfloat,
doc=)

Definition at line 2859 of file bitstring.py.

◆ floatle

floatle
staticinherited
Initial value:
= property(_getfloatle,
doc=)

Definition at line 2868 of file bitstring.py.

◆ floatne

floatne
staticinherited
Initial value:
= property(_getfloatne,
doc=)

Definition at line 2877 of file bitstring.py.

◆ hex

hex
staticinherited
Initial value:
= property(_gethex,
doc=)

Definition at line 2832 of file bitstring.py.

◆ int

int
staticinherited
Initial value:
= property(_getint,
doc=)

Definition at line 2844 of file bitstring.py.

◆ intbe

intbe
staticinherited
Initial value:
= property(_getintbe,
doc=)

Definition at line 2853 of file bitstring.py.

◆ intle

intle
staticinherited
Initial value:
= property(_getintle,
doc=)

Definition at line 2862 of file bitstring.py.

◆ intne

intne
staticinherited
Initial value:
= property(_getintne,
doc=)

Definition at line 2871 of file bitstring.py.

◆ len

len
staticinherited
Initial value:
= property(_getlength,
doc=)

Definition at line 2823 of file bitstring.py.

◆ length

length
staticinherited
Initial value:
= property(_getlength,
doc=)

Definition at line 2826 of file bitstring.py.

◆ oct

oct
staticinherited
Initial value:
= property(_getoct,
doc=)

Definition at line 2838 of file bitstring.py.

◆ pos

pos
static
Initial value:
= property(_getbitpos, _setbitpos,
doc=)

Definition at line 4009 of file bitstring.py.

◆ se

se
staticinherited
Initial value:
= property(_getse,
doc=)

Definition at line 2883 of file bitstring.py.

◆ sie

sie
staticinherited
Initial value:
= property(_getsie,
doc=)

Definition at line 2889 of file bitstring.py.

◆ ue

ue
staticinherited
Initial value:
= property(_getue,
doc=)

Definition at line 2880 of file bitstring.py.

◆ uie

uie
staticinherited
Initial value:
= property(_getuie,
doc=)

Definition at line 2886 of file bitstring.py.

◆ uint

uint
staticinherited
Initial value:
= property(_getuint,
doc=)

Definition at line 2847 of file bitstring.py.

◆ uintbe

uintbe
staticinherited
Initial value:
= property(_getuintbe,
doc=)

Definition at line 2856 of file bitstring.py.

◆ uintle

uintle
staticinherited
Initial value:
= property(_getuintle,
doc=)

Definition at line 2865 of file bitstring.py.

◆ uintne

uintne
staticinherited
Initial value:
= property(_getuintne,
doc=)

Definition at line 2874 of file bitstring.py.


The documentation for this class was generated from the following file: