How to use the bitstring.bits.Bits function in bitstring

To help you get started, we’ve selected a few bitstring examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github scott-griffiths / bitstring / bitstring / bitarray.py View on Github external
else:
            if abs(step) != 1:
                # convert to binary string and use string slicing
                # TODO: Horribly inefficent
                temp = list(self._getbin())
                v = list(bits.Bits(value)._getbin())
                temp.__setitem__(key, v)
                self._setbin_unsafe(''.join(temp))
                return

            # If value is an integer then we want to set the slice to that
            # value rather than initialise a new bitstring of that length.
            if not isinstance(value, numbers.Integral):
                try:
                    # TODO: Better way than calling constructor here?
                    value = bits.Bits(value)
                except TypeError:
                    raise TypeError("Bitstring, integer or string expected. "
                                    "Got {0}.".format(type(value)))
            if not step:
                stop = 0
            else:
                # default stop needs to be a multiple of step
                stop = self.len
                if key.stop is not None:
                    stop -= (self.len % abs(step))
            if key.start is not None:
                start = key.start * abs(step)
                if key.start < 0:
                    start += stop
                if start < 0:
                    start = 0
github scott-griffiths / bitstring / bitstring / bits.py View on Github external
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.

        """
        if count is not None and count < 0:
            raise ValueError("In findall, count must be >= 0.")
        bs = Bits(bs)
        start, end = self._validate_slice(start, end)
        if bytealigned is None:
            bytealigned = bitstring.bytealigned
        c = 0
        while True:
            p = self.find(bs, start, end, bytealigned)
            if not p:
                break
            if count is not None and c >= count:
                return
            c += 1
            yield p[0]
            if bytealigned:
                start = p[0] + 8
            else:
                start = p[0] + 1
github scott-griffiths / bitstring / bitstring / bits.py View on Github external
Raises CreationError if i < 0.

        """
        if i < 0:
            raise bitstring.CreationError("Cannot use negative initialiser for unsigned "
                                "exponential-Golomb.")
        if not i:
            self._setbin_unsafe('1')
            return
        tmp = i + 1
        leadingzeros = -1
        while tmp > 0:
            tmp >>= 1
            leadingzeros += 1
        remainingpart = i + 1 - (1 << leadingzeros)
        binstring = '0' * leadingzeros + '1' + Bits(uint=remainingpart,
                                                             length=leadingzeros).bin
        self._setbin_unsafe(binstring)
github scott-griffiths / bitstring / bitstring / bits.py View on Github external
'uintbe': Bits._setuintbe,
                         'intbe': Bits._setintbe,
                         'floatbe': Bits._setfloat,
                         'uintle': Bits._setuintle,
                         'intle': Bits._setintle,
                         'floatle': Bits._setfloatle,
                         'uintne': Bits._setuintne,
                         'intne': Bits._setintne,
                         'floatne': Bits._setfloatne,
                         }

init_without_length_or_offset = {'bin': Bits._setbin_safe,
                                 'hex': Bits._sethex,
                                 'oct': Bits._setoct,
                                 'ue': Bits._setue,
                                 'se': Bits._setse,
                                 'uie': Bits._setuie,
                                 'sie': Bits._setsie,
                                 'bool': Bits._setbool,
                                 }

class MmapByteArray(object):
    """Looks like a bytearray, but from an mmap."""

    __slots__ = ('filemap', 'filelength', 'source', 'byteoffset', 'bytelength')

    def __init__(self, source, bytelength=None, byteoffset=None):
        self.source = source
        source.seek(0, os.SEEK_END)
        self.filelength = source.tell()
        if byteoffset is None:
            byteoffset = 0
github scott-griffiths / bitstring / bitstring / bits.py View on Github external
sie = property(_getsie,
                   doc="""The bitstring as a signed interleaved exponential-Golomb code. Read only.
                      """)


# Dictionary that maps token names to the function that reads them.
name_to_read = {'uint': Bits._readuint,
                'uintle': Bits._readuintle,
                'uintbe': Bits._readuintbe,
                'uintne': Bits._readuintne,
                'int': Bits._readint,
                'intle': Bits._readintle,
                'intbe': Bits._readintbe,
                'intne': Bits._readintne,
                'float': Bits._readfloat,
                'floatbe': Bits._readfloat, # floatbe is a synonym for float
                'floatle': Bits._readfloatle,
                'floatne': Bits._readfloatne,
                'hex': Bits._readhex,
                'oct': Bits._readoct,
                'bin': Bits._readbin,
                'bits': Bits._readbits,
                'bytes': Bits._readbytes,
                'ue': Bits._readue,
                'se': Bits._readse,
                'uie': Bits._readuie,
                'sie': Bits._readsie,
                'bool': Bits._readbool,
                }

# Dictionaries for mapping init keywords with init functions.
init_with_length_and_offset = {'bytes': Bits._setbytes_safe,
github scott-griffiths / bitstring / bitstring / bits.py View on Github external
'bytes': Bits._readbytes,
                'ue': Bits._readue,
                'se': Bits._readse,
                'uie': Bits._readuie,
                'sie': Bits._readsie,
                'bool': Bits._readbool,
                }

# Dictionaries for mapping init keywords with init functions.
init_with_length_and_offset = {'bytes': Bits._setbytes_safe,
                               'filename': Bits._setfile,
                               }

init_with_length_only = {'uint': Bits._setuint,
                         'int': Bits._setint,
                         'float': Bits._setfloat,
                         'uintbe': Bits._setuintbe,
                         'intbe': Bits._setintbe,
                         'floatbe': Bits._setfloat,
                         'uintle': Bits._setuintle,
                         'intle': Bits._setintle,
                         'floatle': Bits._setfloatle,
                         'uintne': Bits._setuintne,
                         'intne': Bits._setintne,
                         'floatne': Bits._setfloatne,
                         }

init_without_length_or_offset = {'bin': Bits._setbin_safe,
                                 'hex': Bits._sethex,
                                 'oct': Bits._setoct,
                                 'ue': Bits._setue,
                                 'se': Bits._setse,
github scott-griffiths / bitstring / bitstring / bits.py View on Github external
bit, to optimise append etc.

        """
        if isinstance(bs, Bits):
            return bs
        try:
            return cache[(bs, offset)]
        except KeyError:
            if isinstance(bs, basestring):
                b = cls()
                try:
                    _, tokens = tokenparser(bs)
                except ValueError as e:
                    raise bitstring.CreationError(*e.args)
                if tokens:
                    b._append(Bits._init_with_token(*tokens[0]))
                    b._datastore = bitstore.offsetcopy(b._datastore, offset)
                    for token in tokens[1:]:
                        b._append(Bits._init_with_token(*token))
                assert b._assertsanity()
                assert b.len == 0 or b._offset == offset
                cache[(bs, offset)] = b
                return b
        except TypeError:
            # Unhashable type
            pass
        return cls(bs)
github scott-griffiths / bitstring / bitstring / bitarray.py View on Github external
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.

        """
        bs = bits.Bits(bs)
        if not bs.len:
            return self
        if bs is self:
            bs = self.__copy__()
        if pos is None:
            try:
                pos = self._pos
            except AttributeError:
                raise TypeError("insert require a bit position for this type.")
        if pos < 0:
            pos += self.len
        if not 0 <= pos <= self.len:
            raise ValueError("Invalid insert position.")
        self._insert(bs, pos)