Python bitstring.Bits() Examples

The following are 60 code examples for showing how to use bitstring.Bits(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

You may also check out all available functions/classes of the module bitstring , or try the search function .

Example 1
Project: faucet   Author: faucetsdn   File: fakeoftable.py    License: Apache License 2.0 6 votes vote down vote up
def match_to_bits(self, key, val):
        """convert match fields and masks to bits objects.

        this allows for masked matching. Converting all match fields to the
        same object simplifies things (eg __str__).
        """
        if isinstance(val, Bits):
            return val

        def _val_to_bits(conv, val, length):
            if val == -1:
                return Bits(int=-1, length=length)
            return Bits(bytes=conv(val), length=length)

        if key in self.MAC_MATCH_FIELDS:
            return _val_to_bits(addrconv.mac.text_to_bin, val, 48)
        if key in self.IPV4_MATCH_FIELDS:
            return _val_to_bits(addrconv.ipv4.text_to_bin, val, 32)
        if key in self.IPV6_MATCH_FIELDS:
            return _val_to_bits(addrconv.ipv6.text_to_bin, val, 128)
        return Bits(int=int(val), length=64) 
Example 2
Project: pybufrkit   Author: ywangd   File: bitops.py    License: MIT License 6 votes vote down vote up
def write_bytes(self, value, nbytes=None):
        import bitstring
        # TODO: strings are utf-8 from json reading
        if isinstance(value, six.text_type):
            value = value.encode('latin-1')

        value_len = len(value)

        # Ensure the string is under the required data width
        if nbytes is None:
            nbytes = value_len
        else:
            if value_len > nbytes:
                value = value[:nbytes]
            elif value_len < nbytes:
                value += b' ' * (nbytes - value_len)

        # Cannot use string format shortcut, i.e. 'bytes:{}={}' due to the
        # automatic whitespace trimming by bitstring.
        self.bit_stream += bitstring.Bits(bytes=value)
        return value 
Example 3
Project: APIFuzzer   Author: KissPeter   File: custom_fuzzers.py    License: GNU General Public License v3.0 5 votes vote down vote up
def to_bits(self, val):
        return Bits(self.str_to_bytes(val)) 
Example 4
Project: APIFuzzer   Author: KissPeter   File: custom_fuzzers.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _mutate(self):
        if self._step:
            length = self._min_length + self._step * self._current_index
        else:
            length = self._random.randint(self._min_length, self._max_length)
        current_bytes = ''
        for _ in range(length // 8 + 1):
            current_bytes += chr(self._random.randint(0, 255))
        self._current_value = Bits(bytes=strToBytes(current_bytes))[:length] 
Example 5
Project: APIFuzzer   Author: KissPeter   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def transform_data_to_bytes(data_in):
    if isinstance(data_in, float):
        return bytes(int(data_in))
    elif isinstance(data_in, str):
        return bytes(data_in, 'utf-16')
    elif isinstance(data_in, Bits):
        return data_in.tobytes()
    else:
        return bytes(data_in) 
Example 6
Project: IDTxl   Author: pwollstadt   File: test_parity_empirical.py    License: GNU General Public License v3.0 5 votes vote down vote up
def parity(bytestring):
    par = 0
    string = Bits(bytes=bytestring)

    for bit in string:
        par ^= int(bit)

    return par 
Example 7
Project: IDTxl   Author: pwollstadt   File: systemtest_pid_sydney.py    License: GNU General Public License v3.0 5 votes vote down vote up
def parity(bytestring):
    """Return parity function for a bitstring."""
    par = 0
    string = Bits(bytes=bytestring)

    for bit in string:
        par ^= int(bit)

    return par 
Example 8
Project: IntraArchiveDeduplicator   Author: fake-name   File: Test_db_BKTree_2.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def b2i(binaryStringIn):
	if len(binaryStringIn) != 64:
		print("ERROR: Passed string not 64 characters. String length = %s" % len(binaryStringIn))
		print("ERROR: String value '%s'" % binaryStringIn)
		raise ValueError("Input strings must be 64 chars long!")

	val = Bits(bin=binaryStringIn)
	return val.int 
Example 9
Project: IntraArchiveDeduplicator   Author: fake-name   File: Test_db_BKTree_2.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def b2u(binaryStringIn):
	if len(binaryStringIn) != 64:
		print("ERROR: Passed string not 64 characters. String length = %s" % len(binaryStringIn))
		print("ERROR: String value '%s'" % binaryStringIn)
		raise ValueError("Input strings must be 64 chars long!")

	val = Bits(bin=binaryStringIn)
	return val.uint

# Node ID numbers are derived from the list ordering.
# This will generate a single node with 64 children. 
Example 10
Project: IntraArchiveDeduplicator   Author: fake-name   File: Test_Hamming_1.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def b2i(binaryStringIn):
	if len(binaryStringIn) != 64:
		print("ERROR: Passed string not 64 characters. String length = %s" % len(binaryStringIn))
		print("ERROR: String value '%s'" % binaryStringIn)
		raise ValueError("Input strings must be 64 chars long!")

	val = Bits(bin=binaryStringIn)
	return val.int



# Node ID numbers are derived from the list ordering. 
Example 11
Project: IntraArchiveDeduplicator   Author: fake-name   File: Test_BKTree_Issue_2.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def b2i(binaryStringIn):
	if len(binaryStringIn) != 64:
		print("ERROR: Passed string not 64 characters. String length = %s" % len(binaryStringIn))
		print("ERROR: String value '%s'" % binaryStringIn)
		raise ValueError("Input strings must be 64 chars long!")

	val = Bits(bin=binaryStringIn)
	return val.int 
Example 12
Project: IntraArchiveDeduplicator   Author: fake-name   File: Test_db_BKTree_Issue_1.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def b2i(binaryStringIn):
	if len(binaryStringIn) != 64:
		print("ERROR: Passed string not 64 characters. String length = %s" % len(binaryStringIn))
		print("ERROR: String value '%s'" % binaryStringIn)
		raise ValueError("Input strings must be 64 chars long!")

	val = Bits(bin=binaryStringIn)
	return val.int 
Example 13
Project: IntraArchiveDeduplicator   Author: fake-name   File: Test_BKTree.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def b2i(binaryStringIn):
	if len(binaryStringIn) != 64:
		print("ERROR: Passed string not 64 characters. String length = %s" % len(binaryStringIn))
		print("ERROR: String value '%s'" % binaryStringIn)
		raise ValueError("Input strings must be 64 chars long!")

	val = Bits(bin=binaryStringIn)
	return val.int



# Node ID numbers are derived from the list ordering. 
Example 14
Project: IntraArchiveDeduplicator   Author: fake-name   File: Test_BKTree_Issue_1.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def b2i(binaryStringIn):
	if len(binaryStringIn) != 64:
		print("ERROR: Passed string not 64 characters. String length = %s" % len(binaryStringIn))
		print("ERROR: String value '%s'" % binaryStringIn)
		raise ValueError("Input strings must be 64 chars long!")

	val = Bits(bin=binaryStringIn)
	return val.int 
Example 15
Project: IntraArchiveDeduplicator   Author: fake-name   File: Test_BKTree_2.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def b2i(binaryStringIn):
	if len(binaryStringIn) != 64:
		print("ERROR: Passed string not 64 characters. String length = %s" % len(binaryStringIn))
		print("ERROR: String value '%s'" % binaryStringIn)
		raise ValueError("Input strings must be 64 chars long!")

	val = Bits(bin=binaryStringIn)
	return val.int 
Example 16
Project: IntraArchiveDeduplicator   Author: fake-name   File: Test_BKTree_2.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def b2u(binaryStringIn):
	if len(binaryStringIn) != 64:
		print("ERROR: Passed string not 64 characters. String length = %s" % len(binaryStringIn))
		print("ERROR: String value '%s'" % binaryStringIn)
		raise ValueError("Input strings must be 64 chars long!")

	val = Bits(bin=binaryStringIn)
	return val.uint

# Node ID numbers are derived from the list ordering.
# This will generate a single node with 64 children. 
Example 17
Project: IntraArchiveDeduplicator   Author: fake-name   File: Test_db_BKTree.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def b2i(binaryStringIn):
	if len(binaryStringIn) != 64:
		print("ERROR: Passed string not 64 characters. String length = %s" % len(binaryStringIn))
		print("ERROR: String value '%s'" % binaryStringIn)
		raise ValueError("Input strings must be 64 chars long!")

	val = Bits(bin=binaryStringIn)
	return val.int



# Node ID numbers are derived from the list ordering. 
Example 18
Project: faucet   Author: faucetsdn   File: fakeoftable.py    License: Apache License 2.0 5 votes vote down vote up
def _pretty_field_str(self, key, value, mask=None):
        mask_str = ""
        value_int = value
        mask_int = mask
        if isinstance(value, Bits):
            value_int = value.int
        if isinstance(mask, Bits):
            mask_int = mask.int  # pytype: disable=attribute-error
        elif mask is None:
            mask_int = -1
        if key == 'vlan_vid':
            if value_int & ofp.OFPVID_PRESENT == 0:
                result = 'vlan untagged'
            elif key == 'vlan_vid' and mask_int == ofp.OFPVID_PRESENT:
                result = 'vlan tagged'
            else:
                result = str(value_int ^ ofp.OFPVID_PRESENT)
                if mask_int != -1:
                    mask_str = str(mask_int ^ ofp.OFPVID_PRESENT)
        elif isinstance(value, Bits):
            result = self.bits_to_str(key, value)
            if mask is not None and mask_int != -1:
                mask_str = self.bits_to_str(key, mask)
        elif isinstance(value, str):
            result = value
            if mask is not None:
                mask_str = mask
        elif isinstance(value, int):
            if key in self.HEX_FIELDS:
                result = hex(value)
                if mask is not None and mask != -1:
                    mask_str = hex(mask)
            else:
                result = str(value)
                if mask is not None and mask != -1:
                    mask_str = str(mask)
        if mask_str:
            result += "/{}".format(mask_str)
        return result 
Example 19
Project: pybufrkit   Author: ywangd   File: bitops.py    License: MIT License 5 votes vote down vote up
def set_uint(self, value, nbits, bitpos):
        import bitstring
        if nbits // NBITS_PER_BYTE == 0:
            bins = bitstring.Bits(uint=value, length=nbits)
        else:
            bins = bitstring.Bits(uintbe=value, length=24)
        self.bit_stream[bitpos: bitpos + nbits] = bins 
Example 20
Project: swarfarm   Author: PeteAndersen   File: static.py    License: Apache License 2.0 5 votes vote down vote up
def decrypt_images(**kwargs):
    path = kwargs.pop('path', 'herders/static/herders/images')
    for im_path in iglob(f'{path}/**/*.png', recursive=True):
        encrypted = BitStream(filename=im_path)

        # Check if it is 'encrypted'. 8th byte is 0x0B instead of the correct signature 0x0A
        encrypted.pos = 0x07 * 8
        signature = encrypted.peek('uint:8')
        if signature == 0x0B:
            print(f'Decrypting {im_path}')
            # Correct the PNG signature
            encrypted.overwrite('0x0A', encrypted.pos)

            # Replace bits with magic decrypted values
            try:
                while True:
                    pos = encrypted.pos
                    val = encrypted.peek('uint:8')
                    encrypted.overwrite(Bits(uint=com2us_decrypt_values[val], length=8), pos)
            except ReadError:
                # EOF
                pass

            # Write it back to the file
            with open(im_path, 'wb') as f:
                encrypted.tofile(f)

            continue

        # Check for weird jpeg format with extra header junk. Convert to png.
        encrypted.pos = 0
        if encrypted.peek('bytes:5') == b'Joker':
            print(f'Trimming and converting weird JPEG to PNG {im_path}')
            del encrypted[0:16 * 8]

            # Open it as a jpg and resave to disk
            try:
                new_imfile = Image.open(io.BytesIO(encrypted.tobytes()))
                new_imfile.save(im_path)
            except IOError:
                print(f'Unable to open {im_path}') 
Example 21
Project: angr-platforms   Author: angr   File: instrs_riscv.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def bits_to_signed_int(s):
    return Bits(bin=s).int 
Example 22
Project: angr-platforms   Author: angr   File: instrs_msp430.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def bits_to_signed_int(s):
    return Bits(bin=s).int 
Example 23
Project: angr-platforms   Author: angr   File: instrs_msp430.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def parse(self, bitstrm):
        """
        MSP430 instructions can have one or two extension words for 16 bit immediates
        We therefore extend the normal parsing so that we make sure we can
        get another word if we have to.
        """
        data = Instruction.parse(self, bitstrm)
        data['S'] = None
        data['D'] = None
        # We don't always have a source or destination.
        # Theoretically I could put these in the TypeXInstruction classes, but
        # I'm lazy. Note that we resolve these here, as opposed to later, due to
        # needing to fiddle with the bitstream.
        l.debug(data)
        if 's' in data:
            src_mode = int(data['A'], 2)
            if (src_mode == ArchMSP430.Mode.INDEXED_MODE and data['s'] != '0011') \
                    or (data['s'] == '0000' and src_mode == ArchMSP430.Mode.INDIRECT_AUTOINCREMENT_MODE):
                data['S'] = bitstring.Bits(uint=bitstrm.read('uintle:16'), length=16).bin
                self.bitwidth += 16 # pylint: disable=no-member
        if 'd' in data:
            dst_mode = int(data['a'], 2)
            if dst_mode == ArchMSP430.Mode.INDEXED_MODE:
                data['D'] = bitstring.Bits(uint=bitstrm.read('uintle:16'), length=16).bin
                self.bitwidth += 16 # pylint: disable=no-member
        return data 
Example 24
Project: bitstring   Author: scott-griffiths   File: test_bitstring.py    License: MIT License 5 votes vote down vote up
def testAll(self):
        exported = ['ConstBitArray', 'ConstBitStream', 'BitStream', 'BitArray',
                    'Bits', 'BitString', 'pack', 'Error', 'ReadError',
                    'InterpretError', 'ByteAlignError', 'CreationError', 'bytealigned', 'set_lsb0', 'set_msb0']
        self.assertEqual(set(bitstring.__all__), set(exported)) 
Example 25
Project: bitstring   Author: scott-griffiths   File: test_bitstring.py    License: MIT License 5 votes vote down vote up
def testReverseDict(self):
        d = bitstring.BYTE_REVERSAL_DICT
        for i in range(256):
            a = bitstring.Bits(uint=i, length=8)
            b = d[i]
            self.assertEqual(a.bin[::-1], bitstring.Bits(bytes=b).bin) 
Example 26
Project: bitstring   Author: scott-griffiths   File: test_bitstring.py    License: MIT License 5 votes vote down vote up
def testAliases(self):
        self.assertTrue(bitstring.Bits is bitstring.ConstBitArray)
        self.assertTrue(bitstring.BitStream is bitstring.BitString) 
Example 27
Project: bitstring   Author: scott-griffiths   File: test_bitstring.py    License: MIT License 5 votes vote down vote up
def testBaselineMemory(self):
        try:
            import pympler.asizeof.asizeof as size
        except ImportError:
            return
        # These values might be platform dependent, so don't fret too much.
        self.assertEqual(size(bitstring.ConstBitStream([0])), 64)
        self.assertEqual(size(bitstring.Bits([0])), 64)
        self.assertEqual(size(bitstring.BitStream([0])), 64)
        self.assertEqual(size(bitstring.BitArray([0])), 64)
        from bitstring.bitstore import ByteStore
        self.assertEqual(size(ByteStore(bytearray())), 100) 
Example 28
Project: bitstring   Author: scott-griffiths   File: test_bitstring.py    License: MIT License 5 votes vote down vote up
def testConstBitArrayCopy(self):
        import copy
        cba = bitstring.Bits(100)
        cba_copy = copy.copy(cba)
        self.assertTrue(cba is cba_copy) 
Example 29
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreationFromBytes(self):
        s = Bits(bytes=b'\xa0\xff')
        self.assertEqual((s.len, s.hex), (16, 'a0ff'))
        s = Bits(bytes=b'abc', length=0)
        self.assertEqual(s, '') 
Example 30
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreationFromBytesErrors(self):
        with self.assertRaises(bitstring.CreationError):
            Bits(bytes=b'abc', length=25) 
Example 31
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreationFromDataWithOffset(self):
        s1 = Bits(bytes=b'\x0b\x1c\x2f', offset=0, length=20)
        s2 = Bits(bytes=b'\xa0\xb1\xC2', offset=4)
        self.assertEqual((s2.len, s2.hex), (20, '0b1c2'))
        self.assertEqual((s1.len, s1.hex), (20, '0b1c2'))
        self.assertTrue(s1 == s2) 
Example 32
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreationFromHex(self):
        s = Bits(hex='0xA0ff')
        self.assertEqual((s.len, s.hex), (16, 'a0ff'))
        s = Bits(hex='0x0x0X')
        self.assertEqual((s.length, s.hex), (0, '')) 
Example 33
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreationFromHexWithWhitespace(self):
        s = Bits(hex='  \n0 X a  4e       \r3  \n')
        self.assertEqual(s.hex, 'a4e3') 
Example 34
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreationFromBin(self):
        s = Bits(bin='1010000011111111')
        self.assertEqual((s.length, s.hex), (16, 'a0ff'))
        s = Bits(bin='00')[:1]
        self.assertEqual(s.bin, '0')
        s = Bits(bin=' 0000 \n 0001\r ')
        self.assertEqual(s.bin, '00000001') 
Example 35
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreationFromBinWithWhitespace(self):
        s = Bits(bin='  \r\r\n0   B    00   1 1 \t0 ')
        self.assertEqual(s.bin, '00110') 
Example 36
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreationFromOctErrors(self):
        s = Bits('0b00011')
        with self.assertRaises(bitstring.InterpretError):
            s.oct
        with self.assertRaises(bitstring.CreationError):
            Bits('oct=8') 
Example 37
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreationFromUintWithOffset(self):
        with self.assertRaises(bitstring.CreationError):
            Bits(uint=12, length=8, offset=1) 
Example 38
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreationFromUintErrors(self):
        with self.assertRaises(bitstring.CreationError):
            Bits(uint=-1, length=10)
        with self.assertRaises(bitstring.CreationError):
            Bits(uint=12)
        with self.assertRaises(bitstring.CreationError):
            Bits(uint=4, length=2)
        with self.assertRaises(bitstring.CreationError):
            Bits(uint=0, length=0)
        with self.assertRaises(bitstring.CreationError):
            Bits(uint=12, length=-12) 
Example 39
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreationFromIntErrors(self):
        with self.assertRaises(bitstring.CreationError):
            Bits(int=-1, length=0)
        with self.assertRaises(bitstring.CreationError):
            Bits(int=12)
        with self.assertRaises(bitstring.CreationError):
            Bits(int=4, length=3)
        with self.assertRaises(bitstring.CreationError):
            Bits(int=-5, length=3) 
Example 40
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreationFromSe(self):
        for i in range(-100, 10):
            s = Bits(se=i)
            self.assertEqual(s.se, i) 
Example 41
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreationFromSeWithOffset(self):
        with self.assertRaises(bitstring.CreationError):
            Bits(se=-13, offset=1) 
Example 42
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreationFromSeErrors(self):
        with self.assertRaises(bitstring.CreationError):
            Bits(se=-5, length=33)
        s = Bits(bin='001000')
        with self.assertRaises(bitstring.InterpretError):
            s.se 
Example 43
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreationFromUe(self):
        [self.assertEqual(Bits(ue=i).ue, i) for i in range(0, 20)] 
Example 44
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreationFromUeErrors(self):
        with self.assertRaises(bitstring.CreationError):
            Bits(ue=-1)
        with self.assertRaises(bitstring.CreationError):
            Bits(ue=1, length=12)
        s = Bits(bin='10')
        with self.assertRaises(bitstring.InterpretError):
            s.ue 
Example 45
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreationFromBool(self):
        a = Bits('bool=1')
        self.assertEqual(a, 'bool=1')
        b = Bits('bool:1=0')
        self.assertEqual(b, [0])
        c = bitstring.pack('bool=1, 2*bool', 0, 1)
        self.assertEqual(c, '0b101')
        d = bitstring.pack('bool:1=1, 2*bool:1', 1, 0)
        self.assertEqual(d, '0b110') 
Example 46
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreationKeywordError(self):
        with self.assertRaises(bitstring.CreationError):
            Bits(squirrel=5) 
Example 47
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testDataStoreType(self):
        a = Bits('0xf')
        self.assertEqual(type(a._datastore), bitstring.ConstByteStore) 
Example 48
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testEmptyInit(self):
        a = Bits()
        self.assertEqual(a, '') 
Example 49
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testFind(self):
        a = Bits('0xabcd')
        r = a.find('0xbc')
        self.assertEqual(r[0], 4)
        r = a.find('0x23462346246', bytealigned=True)
        self.assertFalse(r) 
Example 50
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testRfind(self):
        a = Bits('0b11101010010010')
        b = a.rfind('0b010')
        self.assertEqual(b[0], 11) 
Example 51
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testFindAll(self):
        a = Bits('0b0010011')
        b = list(a.findall([1]))
        self.assertEqual(b, [2, 5, 6]) 
Example 52
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCut(self):
        s = Bits(30)
        for t in s.cut(3):
            self.assertEqual(t, [0] * 3) 
Example 53
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreation(self):
        s1 = Bits(uie=0)
        s2 = Bits(uie=1)
        self.assertEqual(s1, [1])
        self.assertEqual(s2, [0, 0, 1])
        s1 = Bits(sie=0)
        s2 = Bits(sie=-1)
        s3 = Bits(sie=1)
        self.assertEqual(s1, [1])
        self.assertEqual(s2, [0, 0, 1, 1])
        self.assertEqual(s3, [0, 0, 1, 0]) 
Example 54
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testErrors(self):
        for f in ['sie=100, 0b1001', '0b00', 'uie=100, 0b1001']:
            s = Bits(f)
            with self.assertRaises(bitstring.InterpretError):
                s.sie
            with self.assertRaises(bitstring.InterpretError):
                s.uie
        with self.assertRaises(ValueError):
            Bits(uie=-10) 
Example 55
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        self.a = Bits(filename='smalltestfile')
        self.b = Bits(filename='smalltestfile', offset=16)
        self.c = Bits(filename='smalltestfile', offset=20, length=16)
        self.d = Bits(filename='smalltestfile', offset=20, length=4) 
Example 56
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testUnorderable(self):
        a = Bits(5)
        b = Bits(5)
        with self.assertRaises(TypeError):
            a <  b
        with self.assertRaises(TypeError):
            a >  b
        with self.assertRaises(TypeError):
            a <=  b
        with self.assertRaises(TypeError):
            a >=  b 
Example 57
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testIsInstance(self):
        class SubBits(bitstring.Bits): pass
        a = SubBits()
        self.assertTrue(isinstance(a, SubBits)) 
Example 58
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testClassType(self):
        class SubBits(bitstring.Bits): pass
        self.assertEqual(SubBits().__class__, SubBits) 
Example 59
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testCreation(self):
        a = Bits('pad:10')
        self.assertEqual(a, Bits(10))
        b = Bits('pad:0')
        self.assertEqual(b, Bits())
        c = Bits('0b11, pad:1, 0b111')
        self.assertEqual(c, Bits('0b110111')) 
Example 60
Project: bitstring   Author: scott-griffiths   File: test_bits.py    License: MIT License 5 votes vote down vote up
def testPack(self):
        s = bitstring.pack('0b11, pad:3=5, 0b1')
        self.assertEqual(s.bin, '110001')
        d = bitstring.pack('pad:c', c=12)
        self.assertEqual(d, Bits(12))
        e = bitstring.pack('0xf, uint:12, pad:1, bin, pad:4, 0b10', 0, '111')
        self.assertEqual(e.bin, '11110000000000000111000010')