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

Public Member Functions

def __init__ (self, auto=None, length=None, offset=None, **kwargs)
 
def __new__ (cls, auto=None, length=None, offset=None, **kwargs)
 
def __iadd__ (self, bs)
 
def __copy__ (self)
 
def __setitem__ (self, key, value)
 
def __delitem__ (self, key)
 
def __ilshift__ (self, n)
 
def __irshift__ (self, n)
 
def __imul__ (self, n)
 
def __ior__ (self, bs)
 
def __iand__ (self, bs)
 
def __ixor__ (self, bs)
 
def replace (self, old, new, start=None, end=None, count=None, bytealigned=None)
 
def insert (self, bs, pos=None)
 
def overwrite (self, bs, pos=None)
 
def append (self, bs)
 
def prepend (self, bs)
 
def reverse (self, start=None, end=None)
 
def set (self, value, pos=None)
 
def invert (self, pos=None)
 
def ror (self, bits, start=None, end=None)
 
def rol (self, bits, start=None, end=None)
 
def byteswap (self, fmt=None, start=None, end=None, repeat=True)
 
def clear (self)
 
def copy (self)
 

Protected Attributes

 _pos
 

Properties

property int
 
property uint
 
property float
 
property intbe
 
property uintbe
 
property floatbe
 
property intle
 
property uintle
 
property floatle
 
property intne
 
property uintne
 
property floatne
 
property ue
 
property se
 
property uie
 
property sie
 
property hex
 
property bin
 
property oct
 
property bool
 
property bytes
 

Static Private Attributes

tuple __slots__ = ()
 
None __hash__ = None
 

Detailed Description

A container holding a mutable sequence of bits.

Subclass of the immutable Bits class. Inherits all of its
methods (except __hash__) and adds mutating methods.

Mutating methods:

append() -- Append a bitstring.
byteswap() -- Change byte endianness in-place.
insert() -- Insert a bitstring.
invert() -- Flip bit(s) between one and zero.
overwrite() -- Overwrite a section with a new bitstring.
prepend() -- Prepend a bitstring.
replace() -- Replace occurrences of one bitstring with another.
reverse() -- Reverse bits in-place.
rol() -- Rotate bits to the left.
ror() -- Rotate bits to the right.
set() -- Set bit(s) to 1 or 0.

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.

Special methods:

Mutating operators are available: [], <<=, >>=, +=, *=, &=, |= and ^=
in addition to the inherited [], ==, !=, +, *, ~, <<, >>, &, | and ^.

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 2949 of file bitstring.py.

Constructor & Destructor Documentation

◆ __init__()

def __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'.

Reimplemented from Bits.

Reimplemented in BitStream.

Definition at line 3025 of file bitstring.py.

3025 def __init__(self, auto=None, length=None, offset=None, **kwargs):
3026 """Either specify an 'auto' initialiser:
3027 auto -- a string of comma separated tokens, an integer, a file object,
3028 a bytearray, a boolean iterable or another bitstring.
3029
3030 Or initialise via **kwargs with one (and only one) of:
3031 bytes -- raw data as a string, for example read from a binary file.
3032 bin -- binary string representation, e.g. '0b001010'.
3033 hex -- hexadecimal string representation, e.g. '0x2ef'
3034 oct -- octal string representation, e.g. '0o777'.
3035 uint -- an unsigned integer.
3036 int -- a signed integer.
3037 float -- a floating point number.
3038 uintbe -- an unsigned big-endian whole byte integer.
3039 intbe -- a signed big-endian whole byte integer.
3040 floatbe - a big-endian floating point number.
3041 uintle -- an unsigned little-endian whole byte integer.
3042 intle -- a signed little-endian whole byte integer.
3043 floatle -- a little-endian floating point number.
3044 uintne -- an unsigned native-endian whole byte integer.
3045 intne -- a signed native-endian whole byte integer.
3046 floatne -- a native-endian floating point number.
3047 se -- a signed exponential-Golomb code.
3048 ue -- an unsigned exponential-Golomb code.
3049 sie -- a signed interleaved exponential-Golomb code.
3050 uie -- an unsigned interleaved exponential-Golomb code.
3051 bool -- a boolean (True or False).
3052 filename -- a file which will be opened in binary read-only mode.
3053
3054 Other keyword arguments:
3055 length -- length of the bitstring in bits, if needed and appropriate.
3056 It must be supplied for all integer and float initialisers.
3057 offset -- bit offset to the data. These offset bits are
3058 ignored and this is intended for use when
3059 initialising using 'bytes' or 'filename'.
3060
3061 """
3062 # For mutable BitArrays we always read in files to memory:
3063 if not isinstance(self._datastore, ByteStore):
3064 self._ensureinmemory()
3065

Member Function Documentation

◆ __copy__()

def __copy__ (   self)
Return a new copy of the BitArray.

Reimplemented from Bits.

Reimplemented in BitStream.

Definition at line 3081 of file bitstring.py.

3081 def __copy__(self):
3082 """Return a new copy of the BitArray."""
3083 s_copy = BitArray()
3084 if not isinstance(self._datastore, ByteStore):
3085 # Let them both point to the same (invariant) array.
3086 # If either gets modified then at that point they'll be read into memory.
3087 s_copy._datastore = self._datastore
3088 else:
3089 s_copy._datastore = copy.copy(self._datastore)
3090 return s_copy
3091

◆ __delitem__()

def __delitem__ (   self,
  key 
)
Delete item or range.

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

>>> a = BitArray('0x001122')
>>> del a[1:2:8]
>>> print a
0x0022

Definition at line 3200 of file bitstring.py.

3200 def __delitem__(self, key):
3201 """Delete item or range.
3202
3203 Indices are in units of the step parameter (default 1 bit).
3204 Stepping is used to specify the number of bits in each item.
3205
3206 >>> a = BitArray('0x001122')
3207 >>> del a[1:2:8]
3208 >>> print a
3209 0x0022
3210
3211 """
3212 try:
3213 # A slice
3214 start = 0
3215 step = key.step if key.step is not None else 1
3216 except AttributeError:
3217 # single element
3218 if key < 0:
3219 key += self.len
3220 if not 0 <= key < self.len:
3221 raise IndexError("Slice index out of range.")
3222 self._delete(1, key)
3223 return
3224 else:
3225 if step != 1:
3226 # convert to binary string and use string slicing
3227 # TODO: Horribly inefficent
3228 temp = list(self._getbin())
3229 temp.__delitem__(key)
3230 self._setbin_unsafe(''.join(temp))
3231 return
3232 stop = key.stop
3233 if key.start is not None:
3234 start = key.start
3235 if key.start < 0 and stop is None:
3236 start += self.len
3237 if start < 0:
3238 start = 0
3239 if stop is None:
3240 stop = self.len
3241 if start > stop:
3242 return
3243 stop = min(stop, self.len)
3244 start = max(start, 0)
3245 start = min(start, stop)
3246 self._delete(stop - start, start)
3247 return
3248

◆ __iadd__()

def __iadd__ (   self,
  bs 
)
Append bs to current bitstring. Return self.

bs -- the bitstring to append.

Definition at line 3072 of file bitstring.py.

3072 def __iadd__(self, bs):
3073 """Append bs to current bitstring. Return self.
3074
3075 bs -- the bitstring to append.
3076
3077 """
3078 self.append(bs)
3079 return self
3080

◆ __iand__()

def __iand__ (   self,
  bs 
)

Definition at line 3297 of file bitstring.py.

3297 def __iand__(self, bs):
3298 bs = Bits(bs)
3299 if self.len != bs.len:
3300 raise ValueError("Bitstrings must have the same length "
3301 "for &= operator.")
3302 return self._iand(bs)
3303

◆ __ilshift__()

def __ilshift__ (   self,
  n 
)
Shift bits by n to the left in place. Return self.

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

Definition at line 3249 of file bitstring.py.

3249 def __ilshift__(self, n):
3250 """Shift bits by n to the left in place. Return self.
3251
3252 n -- the number of bits to shift. Must be >= 0.
3253
3254 """
3255 if n < 0:
3256 raise ValueError("Cannot shift by a negative amount.")
3257 if not self.len:
3258 raise ValueError("Cannot shift an empty bitstring.")
3259 if not n:
3260 return self
3261 n = min(n, self.len)
3262 return self._ilshift(n)
3263

◆ __imul__()

def __imul__ (   self,
  n 
)
Concatenate n copies of self in place. Return self.

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

Definition at line 3279 of file bitstring.py.

3279 def __imul__(self, n):
3280 """Concatenate n copies of self in place. Return self.
3281
3282 Called for expressions of the form 'a *= 3'.
3283 n -- The number of concatenations. Must be >= 0.
3284
3285 """
3286 if n < 0:
3287 raise ValueError("Cannot multiply by a negative integer.")
3288 return self._imul(n)
3289

◆ __ior__()

def __ior__ (   self,
  bs 
)

Definition at line 3290 of file bitstring.py.

3290 def __ior__(self, bs):
3291 bs = Bits(bs)
3292 if self.len != bs.len:
3293 raise ValueError("Bitstrings must have the same length "
3294 "for |= operator.")
3295 return self._ior(bs)
3296

◆ __irshift__()

def __irshift__ (   self,
  n 
)
Shift bits by n to the right in place. Return self.

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

Definition at line 3264 of file bitstring.py.

3264 def __irshift__(self, n):
3265 """Shift bits by n to the right in place. Return self.
3266
3267 n -- the number of bits to shift. Must be >= 0.
3268
3269 """
3270 if n < 0:
3271 raise ValueError("Cannot shift by a negative amount.")
3272 if not self.len:
3273 raise ValueError("Cannot shift an empty bitstring.")
3274 if not n:
3275 return self
3276 n = min(n, self.len)
3277 return self._irshift(n)
3278

◆ __ixor__()

def __ixor__ (   self,
  bs 
)

Definition at line 3304 of file bitstring.py.

3304 def __ixor__(self, bs):
3305 bs = Bits(bs)
3306 if self.len != bs.len:
3307 raise ValueError("Bitstrings must have the same length "
3308 "for ^= operator.")
3309 return self._ixor(bs)
3310

◆ __new__()

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

Reimplemented from Bits.

Definition at line 3066 of file bitstring.py.

3066 def __new__(cls, auto=None, length=None, offset=None, **kwargs):
3067 x = super(BitArray, cls).__new__(cls)
3068 y = Bits.__new__(BitArray, auto, length, offset, **kwargs)
3069 x._datastore = y._datastore
3070 return x
3071

◆ __setitem__()

def __setitem__ (   self,
  key,
  value 
)
Set item or range to new value.

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

If the length of the bitstring is changed then pos will be moved
to after the inserted section, otherwise it will remain unchanged.

>>> s = BitArray('0xff')
>>> s[0:1:4] = '0xe'
>>> print s
'0xef'
>>> s[4:4] = '0x00'
>>> print s
'0xe00f'

Definition at line 3092 of file bitstring.py.

3092 def __setitem__(self, key, value):
3093 """Set item or range to new value.
3094
3095 Indices are in units of the step parameter (default 1 bit).
3096 Stepping is used to specify the number of bits in each item.
3097
3098 If the length of the bitstring is changed then pos will be moved
3099 to after the inserted section, otherwise it will remain unchanged.
3100
3101 >>> s = BitArray('0xff')
3102 >>> s[0:1:4] = '0xe'
3103 >>> print s
3104 '0xef'
3105 >>> s[4:4] = '0x00'
3106 >>> print s
3107 '0xe00f'
3108
3109 """
3110 try:
3111 # A slice
3112 start, step = 0, 1
3113 if key.step is not None:
3114 step = key.step
3115 except AttributeError:
3116 # single element
3117 if key < 0:
3118 key += self.len
3119 if not 0 <= key < self.len:
3120 raise IndexError("Slice index out of range.")
3121 if isinstance(value, numbers.Integral):
3122 if not value:
3123 self._unset(key)
3124 return
3125 if value in (1, -1):
3126 self._set(key)
3127 return
3128 raise ValueError("Cannot set a single bit with integer {0}.".format(value))
3129 value = Bits(value)
3130 if value.len == 1:
3131 # TODO: this can't be optimal
3132 if value[0]:
3133 self._set(key)
3134 else:
3135 self._unset(key)
3136 else:
3137 self._delete(1, key)
3138 self._insert(value, key)
3139 return
3140 else:
3141 if step != 1:
3142 # convert to binary string and use string slicing
3143 # TODO: Horribly inefficent
3144 temp = list(self._getbin())
3145 v = list(Bits(value)._getbin())
3146 temp.__setitem__(key, v)
3147 self._setbin_unsafe(''.join(temp))
3148 return
3149
3150 # If value is an integer then we want to set the slice to that
3151 # value rather than initialise a new bitstring of that length.
3152 if not isinstance(value, numbers.Integral):
3153 try:
3154 # TODO: Better way than calling constructor here?
3155 value = Bits(value)
3156 except TypeError:
3157 raise TypeError("Bitstring, integer or string expected. "
3158 "Got {0}.".format(type(value)))
3159 if key.start is not None:
3160 start = key.start
3161 if key.start < 0:
3162 start += self.len
3163 if start < 0:
3164 start = 0
3165 stop = self.len
3166 if key.stop is not None:
3167 stop = key.stop
3168 if key.stop < 0:
3169 stop += self.len
3170 if start > stop:
3171 # The standard behaviour for lists is to just insert at the
3172 # start position if stop < start and step == 1.
3173 stop = start
3174 if isinstance(value, numbers.Integral):
3175 if value >= 0:
3176 value = self.__class__(uint=value, length=stop - start)
3177 else:
3178 value = self.__class__(int=value, length=stop - start)
3179 stop = min(stop, self.len)
3180 start = max(start, 0)
3181 start = min(start, stop)
3182 if (stop - start) == value.len:
3183 if not value.len:
3184 return
3185 if step >= 0:
3186 self._overwrite(value, start)
3187 else:
3188 self._overwrite(value.__getitem__(slice(None, None, 1)), start)
3189 else:
3190 # TODO: A delete then insert is wasteful - it could do unneeded shifts.
3191 # Could be either overwrite + insert or overwrite + delete.
3192 self._delete(stop - start, start)
3193 if step >= 0:
3194 self._insert(value, start)
3195 else:
3196 self._insert(value.__getitem__(slice(None, None, 1)), start)
3197 # pos is now after the inserted piece.
3198 return
3199

◆ append()

def append (   self,
  bs 
)
Append a bitstring to the current bitstring.

bs -- The bitstring to append.

Definition at line 3430 of file bitstring.py.

3430 def append(self, bs):
3431 """Append a bitstring to the current bitstring.
3432
3433 bs -- The bitstring to append.
3434
3435 """
3436 # The offset is a hint to make bs easily appendable.
3437 bs = self._converttobitstring(bs, offset=(self.len + self._offset) % 8)
3438 self._append(bs)
3439

◆ byteswap()

def byteswap (   self,
  fmt = None,
  start = None,
  end = None,
  repeat = True 
)
Change the endianness in-place. Return number of repeats of fmt done.

fmt -- A compact structure string, an integer number of bytes or
       an iterable of integers. Defaults to 0, which byte reverses the
       whole bitstring.
start -- Start bit position, defaults to 0.
end -- End bit position, defaults to self.len.
repeat -- If True (the default) the byte swapping pattern is repeated
          as much as possible.

Definition at line 3566 of file bitstring.py.

3566 def byteswap(self, fmt=None, start=None, end=None, repeat=True):
3567 """Change the endianness in-place. Return number of repeats of fmt done.
3568
3569 fmt -- A compact structure string, an integer number of bytes or
3570 an iterable of integers. Defaults to 0, which byte reverses the
3571 whole bitstring.
3572 start -- Start bit position, defaults to 0.
3573 end -- End bit position, defaults to self.len.
3574 repeat -- If True (the default) the byte swapping pattern is repeated
3575 as much as possible.
3576
3577 """
3578 start, end = self._validate_slice(start, end)
3579 if fmt is None or fmt == 0:
3580 # reverse all of the whole bytes.
3581 bytesizes = [(end - start) // 8]
3582 elif isinstance(fmt, numbers.Integral):
3583 if fmt < 0:
3584 raise ValueError("Improper byte length {0}.".format(fmt))
3585 bytesizes = [fmt]
3586 elif isinstance(fmt, basestring):
3587 m = STRUCT_PACK_RE.match(fmt)
3588 if not m:
3589 raise ValueError("Cannot parse format string {0}.".format(fmt))
3590 # Split the format string into a list of 'q', '4h' etc.
3591 formatlist = re.findall(STRUCT_SPLIT_RE, m.group('fmt'))
3592 # Now deal with multiplicative factors, 4h -> hhhh etc.
3593 bytesizes = []
3594 for f in formatlist:
3595 if len(f) == 1:
3596 bytesizes.append(PACK_CODE_SIZE[f])
3597 else:
3598 bytesizes.extend([PACK_CODE_SIZE[f[-1]]] * int(f[:-1]))
3599 elif isinstance(fmt, collections.abc.Iterable):
3600 bytesizes = fmt
3601 for bytesize in bytesizes:
3602 if not isinstance(bytesize, numbers.Integral) or bytesize < 0:
3603 raise ValueError("Improper byte length {0}.".format(bytesize))
3604 else:
3605 raise TypeError("Format must be an integer, string or iterable.")
3606
3607 repeats = 0
3608 totalbitsize = 8 * sum(bytesizes)
3609 if not totalbitsize:
3610 return 0
3611 if repeat:
3612 # Try to repeat up to the end of the bitstring.
3613 finalbit = end
3614 else:
3615 # Just try one (set of) byteswap(s).
3616 finalbit = start + totalbitsize
3617 for patternend in xrange(start + totalbitsize, finalbit + 1, totalbitsize):
3618 bytestart = patternend - totalbitsize
3619 for bytesize in bytesizes:
3620 byteend = bytestart + bytesize * 8
3621 self._reversebytes(bytestart, byteend)
3622 bytestart += bytesize * 8
3623 repeats += 1
3624 return repeats
3625

◆ clear()

def clear (   self)
Remove all bits, reset to zero length.

Definition at line 3626 of file bitstring.py.

3626 def clear(self):
3627 """Remove all bits, reset to zero length."""
3628 self._clear()
3629

◆ copy()

def copy (   self)
Return a copy of the bitstring.

Definition at line 3630 of file bitstring.py.

3630 def copy(self):
3631 """Return a copy of the bitstring."""
3632 return self._copy()
3633

◆ insert()

def insert (   self,
  bs,
  pos = None 
)
Insert bs at bit position pos.

bs -- The bitstring to insert.
pos -- The bit position to insert at.

Raises ValueError if pos < 0 or pos > self.len.

Definition at line 3378 of file bitstring.py.

3378 def insert(self, bs, pos=None):
3379 """Insert bs at bit position pos.
3380
3381 bs -- The bitstring to insert.
3382 pos -- The bit position to insert at.
3383
3384 Raises ValueError if pos < 0 or pos > self.len.
3385
3386 """
3387 bs = Bits(bs)
3388 if not bs.len:
3389 return self
3390 if bs is self:
3391 bs = self.__copy__()
3392 if pos is None:
3393 try:
3394 pos = self._pos
3395 except AttributeError:
3396 raise TypeError("insert require a bit position for this type.")
3397 if pos < 0:
3398 pos += self.len
3399 if not 0 <= pos <= self.len:
3400 raise ValueError("Invalid insert position.")
3401 self._insert(bs, pos)
3402

◆ invert()

def invert (   self,
  pos = None 
)
Invert one or many bits from 0 to 1 or vice versa.

pos -- Either a single bit position or an iterable of bit positions.
       Negative numbers are treated in the same way as slice indices.

Raises IndexError if pos < -self.len or pos >= self.len.

Definition at line 3499 of file bitstring.py.

3499 def invert(self, pos=None):
3500 """Invert one or many bits from 0 to 1 or vice versa.
3501
3502 pos -- Either a single bit position or an iterable of bit positions.
3503 Negative numbers are treated in the same way as slice indices.
3504
3505 Raises IndexError if pos < -self.len or pos >= self.len.
3506
3507 """
3508 if pos is None:
3509 self._invert_all()
3510 return
3511 if not isinstance(pos, collections.abc.Iterable):
3512 pos = (pos,)
3513 length = self.len
3514
3515 for p in pos:
3516 if p < 0:
3517 p += length
3518 if not 0 <= p < length:
3519 raise IndexError("Bit position {0} out of range.".format(p))
3520 self._invert(p)
3521

◆ overwrite()

def overwrite (   self,
  bs,
  pos = None 
)
Overwrite with bs at bit position pos.

bs -- The bitstring to overwrite with.
pos -- The bit position to begin overwriting from.

Raises ValueError if pos < 0 or pos + bs.len > self.len

Definition at line 3403 of file bitstring.py.

3403 def overwrite(self, bs, pos=None):
3404 """Overwrite with bs at bit position pos.
3405
3406 bs -- The bitstring to overwrite with.
3407 pos -- The bit position to begin overwriting from.
3408
3409 Raises ValueError if pos < 0 or pos + bs.len > self.len
3410
3411 """
3412 bs = Bits(bs)
3413 if not bs.len:
3414 return
3415 if pos is None:
3416 try:
3417 pos = self._pos
3418 except AttributeError:
3419 raise TypeError("overwrite require a bit position for this type.")
3420 if pos < 0:
3421 pos += self.len
3422 if pos < 0 or pos + bs.len > self.len:
3423 raise ValueError("Overwrite exceeds boundary of bitstring.")
3424 self._overwrite(bs, pos)
3425 try:
3426 self._pos = pos + bs.len
3427 except AttributeError:
3428 pass
3429

◆ prepend()

def prepend (   self,
  bs 
)
Prepend a bitstring to the current bitstring.

bs -- The bitstring to prepend.

Reimplemented in BitStream.

Definition at line 3440 of file bitstring.py.

3440 def prepend(self, bs):
3441 """Prepend a bitstring to the current bitstring.
3442
3443 bs -- The bitstring to prepend.
3444
3445 """
3446 bs = Bits(bs)
3447 self._prepend(bs)
3448

◆ replace()

def replace (   self,
  old,
  new,
  start = None,
  end = None,
  count = None,
  bytealigned = None 
)
Replace all occurrences of old with new in place.

Returns number of replacements made.

old -- The bitstring to replace.
new -- The replacement bitstring.
start -- Any occurrences that start before this will not be replaced.
         Defaults to 0.
end -- Any occurrences that finish after this will not be replaced.
       Defaults to self.len.
count -- The maximum number of replacements to make. Defaults to
         replace all occurrences.
bytealigned -- If True replacements will only be made on byte
               boundaries.

Raises ValueError if old is empty or if start or end are
out of range.

Definition at line 3311 of file bitstring.py.

3312 bytealigned=None):
3313 """Replace all occurrences of old with new in place.
3314
3315 Returns number of replacements made.
3316
3317 old -- The bitstring to replace.
3318 new -- The replacement bitstring.
3319 start -- Any occurrences that start before this will not be replaced.
3320 Defaults to 0.
3321 end -- Any occurrences that finish after this will not be replaced.
3322 Defaults to self.len.
3323 count -- The maximum number of replacements to make. Defaults to
3324 replace all occurrences.
3325 bytealigned -- If True replacements will only be made on byte
3326 boundaries.
3327
3328 Raises ValueError if old is empty or if start or end are
3329 out of range.
3330
3331 """
3332 old = Bits(old)
3333 new = Bits(new)
3334 if not old.len:
3335 raise ValueError("Empty bitstring cannot be replaced.")
3336 start, end = self._validate_slice(start, end)
3337 if bytealigned is None:
3338 bytealigned = globals()['bytealigned']
3339 # Adjust count for use in split()
3340 if count is not None:
3341 count += 1
3342 sections = self.split(old, start, end, count, bytealigned)
3343 lengths = [s.len for s in sections]
3344 if len(lengths) == 1:
3345 # Didn't find anything to replace.
3346 return 0 # no replacements done
3347 if new is self:
3348 # Prevent self assignment woes
3349 new = copy.copy(self)
3350 positions = [lengths[0] + start]
3351 for k in lengths[1:-1]:
3352 # Next position is the previous one plus the length of the next section.
3353 positions.append(positions[-1] + k)
3354 # We have all the positions that need replacements. We do them
3355 # in reverse order so that they won't move around as we replace.
3356 positions.reverse()
3357 try:
3358 # Need to calculate new pos, if this is a bitstream
3359 newpos = self._pos
3360 for p in positions:
3361 self[p:p + old.len] = new
3362 if old.len != new.len:
3363 diff = new.len - old.len
3364 for p in positions:
3365 if p >= newpos:
3366 continue
3367 if p + old.len <= newpos:
3368 newpos += diff
3369 else:
3370 newpos = p
3371 self._pos = newpos
3372 except AttributeError:
3373 for p in positions:
3374 self[p:p + old.len] = new
3375 assert self._assertsanity()
3376 return len(lengths) - 1
3377

◆ reverse()

def reverse (   self,
  start = None,
  end = None 
)
Reverse bits in-place.

start -- Position of first bit to reverse. Defaults to 0.
end -- One past the position of the last bit to reverse.
       Defaults to self.len.

Using on an empty bitstring will have no effect.

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

Definition at line 3449 of file bitstring.py.

3449 def reverse(self, start=None, end=None):
3450 """Reverse bits in-place.
3451
3452 start -- Position of first bit to reverse. Defaults to 0.
3453 end -- One past the position of the last bit to reverse.
3454 Defaults to self.len.
3455
3456 Using on an empty bitstring will have no effect.
3457
3458 Raises ValueError if start < 0, end > self.len or end < start.
3459
3460 """
3461 start, end = self._validate_slice(start, end)
3462 if start == 0 and end == self.len:
3463 self._reverse()
3464 return
3465 s = self._slice(start, end)
3466 s._reverse()
3467 self[start:end] = s
3468

◆ rol()

def rol (   self,
  bits,
  start = None,
  end = None 
)
Rotate bits to the left in-place.

bits -- The number of bits to rotate by.
start -- Start of slice to rotate. Defaults to 0.
end -- End of slice to rotate. Defaults to self.len.

Raises ValueError if bits < 0.

Definition at line 3544 of file bitstring.py.

3544 def rol(self, bits, start=None, end=None):
3545 """Rotate bits to the left in-place.
3546
3547 bits -- The number of bits to rotate by.
3548 start -- Start of slice to rotate. Defaults to 0.
3549 end -- End of slice to rotate. Defaults to self.len.
3550
3551 Raises ValueError if bits < 0.
3552
3553 """
3554 if not self.len:
3555 raise Error("Cannot rotate an empty bitstring.")
3556 if bits < 0:
3557 raise ValueError("Cannot rotate left by negative amount.")
3558 start, end = self._validate_slice(start, end)
3559 bits %= (end - start)
3560 if not bits:
3561 return
3562 lhs = self._slice(start, start + bits)
3563 self._delete(bits, start)
3564 self._insert(lhs, end - bits)
3565

◆ ror()

def ror (   self,
  bits,
  start = None,
  end = None 
)
Rotate bits to the right in-place.

bits -- The number of bits to rotate by.
start -- Start of slice to rotate. Defaults to 0.
end -- End of slice to rotate. Defaults to self.len.

Raises ValueError if bits < 0.

Definition at line 3522 of file bitstring.py.

3522 def ror(self, bits, start=None, end=None):
3523 """Rotate bits to the right in-place.
3524
3525 bits -- The number of bits to rotate by.
3526 start -- Start of slice to rotate. Defaults to 0.
3527 end -- End of slice to rotate. Defaults to self.len.
3528
3529 Raises ValueError if bits < 0.
3530
3531 """
3532 if not self.len:
3533 raise Error("Cannot rotate an empty bitstring.")
3534 if bits < 0:
3535 raise ValueError("Cannot rotate right by negative amount.")
3536 start, end = self._validate_slice(start, end)
3537 bits %= (end - start)
3538 if not bits:
3539 return
3540 rhs = self._slice(end - bits, end)
3541 self._delete(bits, end - bits)
3542 self._insert(rhs, start)
3543

◆ set()

def set (   self,
  value,
  pos = None 
)
Set one or many bits to 1 or 0.

value -- If True bits are set to 1, otherwise they are set to 0.
pos -- Either a single bit position or an iterable of bit positions.
       Negative numbers are treated in the same way as slice indices.
       Defaults to the entire bitstring.

Raises IndexError if pos < -self.len or pos >= self.len.

Definition at line 3469 of file bitstring.py.

3469 def set(self, value, pos=None):
3470 """Set one or many bits to 1 or 0.
3471
3472 value -- If True bits are set to 1, otherwise they are set to 0.
3473 pos -- Either a single bit position or an iterable of bit positions.
3474 Negative numbers are treated in the same way as slice indices.
3475 Defaults to the entire bitstring.
3476
3477 Raises IndexError if pos < -self.len or pos >= self.len.
3478
3479 """
3480 f = self._set if value else self._unset
3481 if pos is None:
3482 pos = xrange(self.len)
3483 try:
3484 length = self.len
3485 for p in pos:
3486 if p < 0:
3487 p += length
3488 if not 0 <= p < length:
3489 raise IndexError("Bit position {0} out of range.".format(p))
3490 f(p)
3491 except TypeError:
3492 # Single pos
3493 if pos < 0:
3494 pos += self.len
3495 if not 0 <= pos < length:
3496 raise IndexError("Bit position {0} out of range.".format(pos))
3497 f(pos)
3498

Member Data Documentation

◆ __hash__

None __hash__ = None
staticprivate

Definition at line 3023 of file bitstring.py.

◆ __slots__

tuple __slots__ = ()
staticprivate

Definition at line 3020 of file bitstring.py.

◆ _pos

_pos
protected

Definition at line 3371 of file bitstring.py.

Property Documentation

◆ bin

property bin
static
Initial value:
= property(Bits._getbin, Bits._setbin_safe,
doc=)

Definition at line 3685 of file bitstring.py.

◆ bool

property bool
static
Initial value:
= property(Bits._getbool, Bits._setbool,
doc=)

Definition at line 3691 of file bitstring.py.

◆ bytes

property bytes
static
Initial value:
= property(Bits._getbytes, Bits._setbytes_safe,
doc=)

Definition at line 3694 of file bitstring.py.

◆ float

property float
static
Initial value:
= property(Bits._getfloat, Bits._setfloat,
doc=)

Definition at line 3640 of file bitstring.py.

◆ floatbe

property floatbe
static
Initial value:
= property(Bits._getfloat, Bits._setfloat,
doc=)

Definition at line 3649 of file bitstring.py.

◆ floatle

property floatle
static
Initial value:
= property(Bits._getfloatle, Bits._setfloatle,
doc=)

Definition at line 3658 of file bitstring.py.

◆ floatne

property floatne
static
Initial value:
= property(Bits._getfloatne, Bits._setfloatne,
doc=)

Definition at line 3667 of file bitstring.py.

◆ hex

property hex
static
Initial value:
= property(Bits._gethex, Bits._sethex,
doc=)

Definition at line 3682 of file bitstring.py.

◆ int

property int
static
Initial value:
= property(Bits._getint, Bits._setint,
doc=)

Definition at line 3634 of file bitstring.py.

◆ intbe

property intbe
static
Initial value:
= property(Bits._getintbe, Bits._setintbe,
doc=)

Definition at line 3643 of file bitstring.py.

◆ intle

property intle
static
Initial value:
= property(Bits._getintle, Bits._setintle,
doc=)

Definition at line 3652 of file bitstring.py.

◆ intne

property intne
static
Initial value:
= property(Bits._getintne, Bits._setintne,
doc=)

Definition at line 3661 of file bitstring.py.

◆ oct

property oct
static
Initial value:
= property(Bits._getoct, Bits._setoct,
doc=)

Definition at line 3688 of file bitstring.py.

◆ se

property se
static
Initial value:
= property(Bits._getse, Bits._setse,
doc=)

Definition at line 3673 of file bitstring.py.

◆ sie

property sie
static
Initial value:
= property(Bits._getsie, Bits._setsie,
doc=)

Definition at line 3679 of file bitstring.py.

◆ ue

property ue
static
Initial value:
= property(Bits._getue, Bits._setue,
doc=)

Definition at line 3670 of file bitstring.py.

◆ uie

property uie
static
Initial value:
= property(Bits._getuie, Bits._setuie,
doc=)

Definition at line 3676 of file bitstring.py.

◆ uint

property uint
static
Initial value:
= property(Bits._getuint, Bits._setuint,
doc=)

Definition at line 3637 of file bitstring.py.

◆ uintbe

property uintbe
static
Initial value:
= property(Bits._getuintbe, Bits._setuintbe,
doc=)

Definition at line 3646 of file bitstring.py.

◆ uintle

property uintle
static
Initial value:
= property(Bits._getuintle, Bits._setuintle,
doc=)

Definition at line 3655 of file bitstring.py.

◆ uintne

property uintne
static
Initial value:
= property(Bits._getuintne, Bits._setuintne,
doc=)

Definition at line 3664 of file bitstring.py.


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