Tibs#
The Tibs class is an immutable container for binary data. The class’s methods are detailed below. Python protocol methods do not render especially well through autodoc, so they are summarized here:
[]indexes bits asboolvalues and slices asTibsinstances.insearches for a promoted bit pattern.==and!=compare by bit value.+concatenate promoted bit sequences.*repeat the bit sequence.<<: Left bit shift, e.g.s = t << 3>>: Right bit shift, e.g.s = t >> 3&bitwise AND.|bitwise OR.^bitwise XOR.~inverts every bit.
- class Tibs(auto=None)#
An immutable container of binary data.
The constructor is a convenient way to delegate to the
from_string,from_bytesorfrom_boolsbuilder methods, depending on the type ofauto.Tibs('0x13')- Equivalent toTibs.from_string('0x13').Tibs([1, 0])- Equivalent toTibs.from_bools([1, 0]).Tibs(b'hello')- Equivalent toTibs.from_bytes(b'hello').
Otherwise, to construct use a builder ‘from’ method:
Tibs.from_bin(s)- Create from a binary string, optionally starting with ‘0b’.Tibs.from_oct(s)- Create from an octal string, optionally starting with ‘0o’.Tibs.from_hex(s)- Create from a hex string, optionally starting with ‘0x’.Tibs.from_u(u, length, [byte_order])- Create from an unsigned int to a given length.Tibs.from_i(i, length, [byte_order])- Create from a signed int to a given length.Tibs.from_f(f, length, [byte_order])- Create from an IEEE float to a 16, 32 or 64 bit length.Tibs.from_bytes(b)- Create directly from abytes,bytearrayormemoryviewobject.Tibs.from_string(s)- Use a formatted string.Tibs.from_bools(iterable)- Convert each element initerableto a bool.Tibs.from_zeros(length)- Initialise withlength0bits.Tibs.from_ones(length)- Initialise withlength1bits.Tibs.from_random(length, [secure, seed])- Initialise withlengthrandomly set bits.Tibs.from_joined(iterable)- Concatenate an iterable of objects.
- all()#
Return True if all bits are equal to 1, otherwise return False.
- Returns:
Trueif all bits are 1, otherwiseFalse.
>>> Tibs('0b1111').all() True >>> Tibs('0b1011').all() False
- any()#
Return True if any bits are equal to 1, otherwise return False.
- Returns:
Trueif any bits are 1, otherwiseFalse.
>>> Tibs('0b0000').any() False >>> Tibs('0b1000').any() True
- byte_swapped(byte_length=None, start=None, end=None)#
Return a new instance with the byte order swapped.
The selected slice will be byte-swapped. It must be a multiple of byte_length long.
- Parameters:
byte_length (int | None) – An int giving the number of bytes in each swap, or None (the default) to do a single reverse over the selected slice.
start (int | None) – Start of slice to byte-swap. Defaults to 0.
end (int | None) – End of slice to byte-swap. Defaults to len(self).
- Returns:
Tibs
>>> a = Tibs('0x12345678') >>> b = a.byte_swapped(2) >>> b Tibs('0x34127856')
- chunks(chunk_size, count=None)#
Return a list of Tibs by cutting into chunks.
- Parameters:
chunk_size (int) – The size in bits of the chunks to create.
count (int | None) – If specified, at most count items are created. Default is to cut as many times as possible.
- Returns:
A list of Tibs chunks.
>>> Tibs('0b110011').chunks(2) [Tibs('0b11'), Tibs('0b00'), Tibs('0b11')]
- chunks_iter(chunk_size, count=None)#
Return an iterator by cutting into Tibs chunks.
- Parameters:
chunk_size (int) – The size in bits of the chunks to generate.
count (int | None) – If specified, at most count items are generated. Default is to cut as many times as possible.
- Returns:
A generator yielding Tibs chunks.
>>> list(Tibs('0b110011').chunks_iter(2)) [Tibs('0b11'), Tibs('0b00'), Tibs('0b11')]
- count(value=None, start=None, end=None, byte_aligned=False, mask=None)#
Counts the total number of occurrences of a bit pattern.
- Parameters:
value (object | None) – Either something that can be converted to a
Tibs, or a single bit (one of0,1,FalseorTrue). Defaults to counting the set bits.start (int | None) – The start of the slice to count within. Defaults to 0.
end (int | None) – The end of the slice to count within. Defaults to len(self).
byte_aligned (bool) – If
True, only occurrences on byte boundaries are counted. Defaults toFalse.mask (object | None) – If present, only the bits set in the mask need to match. Defaults to
None.
- Returns:
The number of times the bit pattern is found.
- Raises:
ValueError – if the slice parameters are invalid, or if the mask length doesn’t match the length of the value.
With no
valuethis counts the set bits, socount()is the same ascount(1).>>> Tibs('0xef').count() 7 >>> Tibs('0xef').count(1, 0, 4) 3 >>> Tibs.from_bin('0011010101100').count('0b01') 4
- count_and(other)#
Count the bits set in both this Tibs and another.
Equivalent to
(self & other).count(1), but without building the intermediateTibs.- Parameters:
other (object) – The other bits. This can be anything promotable to
Tibs.- Returns:
The number of positions set in both.
- Raises:
ValueError – if the two Tibs have differing lengths.
>>> Tibs('0b1100').count_and('0b1010') 1
- count_andnot(other)#
Count the bits set in this Tibs but not in another.
Equivalent to
self.count(1) - self.count_and(other), but in a single pass.- Parameters:
other (object) – The other bits. This can be anything promotable to
Tibs.- Returns:
The number of positions set here but not in the other.
- Raises:
ValueError – if the two Tibs have differing lengths.
>>> Tibs('0b1100').count_andnot('0b1010') 1
- count_or(other)#
Count the bits set in either this Tibs or another.
Equivalent to
(self | other).count(1), but without building the intermediateTibs.- Parameters:
other (object) – The other bits. This can be anything promotable to
Tibs.- Returns:
The number of positions set in either.
- Raises:
ValueError – if the two Tibs have differing lengths.
>>> Tibs('0b1100').count_or('0b1010') 3
- count_xor(other)#
Count the bits that differ between this Tibs and another.
This is the Hamming distance. Equivalent to
(self ^ other).count(1), but without building the intermediateTibs.- Parameters:
other (object) – The other bits. This can be anything promotable to
Tibs.- Returns:
The number of positions where the two differ.
- Raises:
ValueError – if the two Tibs have differing lengths.
>>> Tibs('0b1100').count_xor('0b1010') 2
- decode(b, /)#
Create a Tibs by decoding bytes created via Tibs.encode()
- Parameters:
b (bytes | bytearray) – The encoded bytes to decode.
- Returns:
A new Tibs.
- Raises:
ValueError – for badly formed, truncated or extended input bytes.
>>> Tibs.decode(Tibs('0b101').encode()) Tibs('0b101')
- deposited(value, mask)#
Return a new Tibs with a scattered bit field written into it.
This is the immutable equivalent of
Mutibs.deposit(), and the inverse ofextract(): the bits ofvalueare written into the positions set inmask, and the other bits are copied unchanged.- Parameters:
value (object) – The bits to deposit. This can be anything promotable to
Tibs, and must bemask.count()bits long.mask (object) – The mask selecting which positions to write. This can be anything promotable to
Tibs, and must be the same length asself.
- Returns:
A new Tibs.
- Raises:
ValueError – if the mask length doesn’t match the length of
self, orvalueis notmask.count()bits long.
>>> Tibs('0b11010110').deposited('0b111', '0b10110000').bin '11110110'
- encode(codec=None)#
Encode the tibs as a bytes instance.
The bit length and the bit indexing are stored in the encoded bytes.
The bytes instance can be used to recreate the Tibs exactly - see
Tibs.decode().Use
Codec.Rawwhen the encoded bytes themselves need to be a stable, canonical representation. The defaultCodec.Autochooses a valid encoding for compactness and may produce different bytes for the same value in a future release.- Parameters:
codec (Codec) – The codec to use. Defaults to Codec.Auto.
- Returns:
The encoded bytes.
>>> t = Tibs('0b101') >>> b = t.encode() >>> b b'\x8d' >>> Tibs.decode(b) Tibs('0b101')
- ends_with(suffix)#
Return whether the current Tibs ends with suffix.
- Parameters:
suffix (object) – The bits to search for. This can be anything promotable to
Tibs.- Returns:
True if the Tibs ends with the suffix, otherwise False.
>>> Tibs('0b101100').ends_with('0b100') True >>> Tibs('0b101100').ends_with('0b101') False
- extract(mask)#
Read the bits at the positions set in a mask, packed together.
This reads a bit field whose bits are scattered through the Tibs by the mask, the way
field()reads a contiguous one. The result has one bit for each set bit of the mask, in order.- Parameters:
mask (object) – The mask selecting which bits to read. This can be anything promotable to
Tibs, and must be the same length asself.- Returns:
A new Tibs of length
mask.count().- Raises:
ValueError – if the mask length doesn’t match the length of
self.
>>> Tibs('0b11010110').extract('0b10110000') Tibs('0b101')
- field(a, b)#
Extract a field using inclusive MSB0 bit labels.
aandbmust be zero or positive bit labels. The two endpoints are inclusive and may be provided in either order. This is equivalent toself.msb0.field(a, b).- Parameters:
a (int) – One non-negative inclusive field endpoint.
b (int) – The other non-negative inclusive field endpoint.
- Returns:
A new
View.
- find(needle, start=None, end=None, byte_aligned=False, mask=None)#
Find first occurrence of a bit sequence.
Returns the bit position if found, or None if not found.
- Parameters:
needle (object) – The bit sequence to find. This can be anything promotable to
Tibs.start (int | None) – The starting bit position. Defaults to 0.
end (int | None) – The end position. Defaults to len(self).
byte_aligned (bool) – If
True, the Tibs will only be found on byte boundaries.mask (object | None) – If present, only the bits set in the mask need to match. Defaults to
None.
- Returns:
The bit position if found, or None if not found.
- Raises:
ValueError – if
needleis empty, if the slice parameters are invalid, or if the mask length doesn’t match the needle length.
The
maskmust be the same length asneedle. Only the bits set in it are compared, so the bits ofneedleunder a zero mask bit are ignored and can be anything.>>> Tibs('0xc3e').find('0b1111') 6 >>> Tibs('0x3a5f').find('0x0f', mask='0x0f', byte_aligned=True) 8
- find_all(needle, start=None, end=None, byte_aligned=False, mask=None)#
Find all occurrences of a bit sequence.
- Parameters:
needle (object) – The bit sequence to find. This can be anything promotable to
Tibs.start (int | None) – The starting bit position of the slice to search. Defaults to 0.
end (int | None) – The end bit position of the slice to search. Defaults to len(self).
byte_aligned (bool) – If
True, the Tibs will only be found on byte boundaries. Defaults toFalse.mask (object | None) – If present, only the bits set in the mask need to match. Defaults to
None.
- Returns:
A list of bit positions.
- Raises:
ValueError – if needle is empty, if start or end are out of range, if end is before start or if the mask length doesn’t match the needle length.
All occurrences of needle are found, even if they overlap.
>>> Tibs('0b10111011').find_all('0b11') [2, 3, 6] >>> Tibs('0x1f2f3a').find_all('0x0f', mask='0x0f', byte_aligned=True) [0, 8]
- find_all_iter(needle, start=None, end=None, byte_aligned=False, mask=None)#
Find all occurrences of a bit sequence, returning an iterator of bit positions.
- Parameters:
needle (object) – The bit sequence to find. This can be anything promotable to
Tibs.start (int | None) – The starting bit position of the slice to search. Defaults to 0.
end (int | None) – The end bit position of the slice to search. Defaults to len(self).
byte_aligned (bool) – If
True, the Tibs will only be found on byte boundaries. Defaults toFalse.mask (object | None) – If present, only the bits set in the mask need to match. Defaults to
None.
- Returns:
A generator yielding bit positions.
- Raises:
ValueError – if needle is empty, if start or end are out of range, if end is before start or if the mask length doesn’t match the needle length.
All occurrences of needle are found, even if they overlap.
Note that this method is not available for
Mutibsas its value could change while the generator is still active. For that case, convert to aTibsfirst withMutibs.to_tibs(), or useMutibs.as_tibs()if you no longer need the mutable object.>>> list(Tibs('0b10111011').find_all_iter('0b11')) [2, 3, 6]
- from_bin(s, /)#
Create a new instance from a binary string.
- Parameters:
s (str) – A string of
0and1s, optionally preceded with0band optionally containing underscores.- Returns:
A newly constructed
Tibs.
a = Tibs.from_bin("0000_1111_0101")
- from_bools(iterable, /)#
Create a new instance from an iterable by converting each element to a bool.
- Parameters:
iterable (Iterable) – The iterable to convert to a
Tibs.- Returns:
A newly constructed
Tibs.
a = Tibs.from_bools([False, 0, 1, "Steven"]) # binary 0011
- from_bytes(data, /, offset=None, length=None)#
Create a new instance from a bytes object.
- Parameters:
data (bytes | bytearray | memoryview) – The bytes, bytearray or memoryview object to convert to a
Tibs.offset (int | None) – The bit offset from the start. Defaults to zero.
length (int | None) – The bit length to use. Defaults to the whole of the data.
- Returns:
A newly constructed
Tibs.
a = Tibs.from_bytes(b"some_bytes_maybe_from_a_file")
- from_f(f, /, length, byte_order=None)#
Create a new instance from a floating point number.
- Parameters:
f (float) – A floating point value.
length (int) – The bit length to create. Must be 16, 32 or 64.
byte_order (ByteOrder) – The byte order used to store the float. Defaults to ByteOrder.Unspecified.
- Returns:
A newly constructed
Tibs.
>>> Tibs.from_f(1.5, length=32) Tibs('0x3fc00000')
- from_hex(s, /)#
Create a new instance from a hexadecimal string.
- Parameters:
s (str) – A string of hexadecimal digits, optionally preceded with
0xand optionally containing underscores.- Returns:
A newly constructed
Tibs.
>>> Tibs.from_hex("0f") Tibs('0x0f')
- from_i(i, /, length, byte_order=None)#
Create a new instance from a signed integer.
- Parameters:
i (int) – A signed integer.
length (int) – The bit length to create. Can be any positive number of bits.
byte_order (ByteOrder) – The byte order used to store the integer. Defaults to ByteOrder.Unspecified.
- Returns:
A newly constructed
Tibs.- Raises:
ValueError – if the integer doesn’t fit in the length given.
>>> Tibs.from_i(-2, length=4) Tibs('0xe')
- from_joined(iterable, /)#
Create a new instance by concatenating a sequence of Tibs objects.
This method concatenates a sequence of Tibs objects into a single Tibs object.
- Parameters:
iterable (Iterable) – An iterable to concatenate. Items can be anything that can be promoted to a Tibs.
- Returns:
A newly constructed
Tibs.
a = Tibs.from_joined(['0x01', [1, 0], b'some_bytes'])
- from_oct(s, /)#
Create a new instance from an octal string.
- Parameters:
s (str) – A string of octal digits, optionally preceded with
0oand optionally containing underscores.- Returns:
A newly constructed
Tibs.
>>> Tibs.from_oct("17") Tibs('0b001111')
- from_ones(length, /)#
Create a new instance with all bits set to ‘1’.
- Parameters:
length (int) – The number of bits to set.
- Returns:
A Tibs object with all bits set to one.
>>> Tibs.from_ones(5) Tibs('0b11111')
- from_random(length, /, secure=False, seed=None)#
Create a new instance with all bits randomly set.
- Parameters:
length (int) – The number of bits to set. Must be non-negative.
secure (bool) – If
True, use the OS’s cryptographically secure generator. Default isFalse.seed (bytes | bytearray | None) – A bytes or bytearray to use as an optional seed, only if
secureisFalse.
- Returns:
A newly constructed
Tibswith random data.
The ‘secure’ option uses the OS’s random data source, so will be slower and could potentially fail.
a = Tibs.from_random(1000000) # A million random bits b = Tibs.from_random(100, seed=b'a_seed')
- from_string(s, /)#
Create a new instance from a formatted string.
- Parameters:
s (str) – The formatted string to convert. This can begin with ‘0b’, ‘0o’ or ‘0x’ to indicate binary, octal or hexadecimal, and commas can be used to separate items.
- Returns:
A newly constructed
Tibs.
a = Tibs.from_string("0xff01") b = Tibs.from_string("0o775, 0b1")
The
__init__method can also redirect tofrom_string:a = Tibs("0xff01")
- from_u(u, /, length, byte_order=None)#
Create a new instance from an unsigned integer.
- Parameters:
u (int) – An unsigned integer.
length (int) – The bit length to create. Can be any positive number of bits.
byte_order (ByteOrder) – The byte order used to store the integer. Defaults to ByteOrder.Unspecified.
- Returns:
A newly constructed
Tibs.- Raises:
ValueError – if the integer doesn’t fit in the length given.
>>> Tibs.from_u(15, length=8) Tibs('0x0f')
- from_value(dtype, value, /)#
Create a new instance by encoding one Python value with a dtype.
- Parameters:
dtype (Dtype | str) – The value encoding to use.
value (object) – The value to encode.
- Returns:
A newly constructed
Tibs.
>>> Tibs.from_value("u8", 15) Tibs('0x0f')
- from_values(dtype, iterable, /)#
Create a new instance by encoding and concatenating values with a dtype.
- Parameters:
dtype (Dtype | str) – The value encoding to use for each item.
iterable (Iterable) – The values to encode.
- Returns:
A newly constructed
Tibs.
>>> Tibs.from_values("u8", [1, 2, 3]) Tibs('0x010203')
- from_zeros(length, /)#
Create a new instance with all bits set to ‘0’.
- Parameters:
length (int) – The number of bits to set.
- Returns:
A Tibs object with all bits set to zero.
a = Tibs.from_zeros(500) # 500 zero bits
- inserted(pos, bs, /)#
Insert bits at position pos and return a new Tibs.
This is the immutable equivalent of
Mutibs.insert().- Parameters:
pos (int) – The bit position to insert at. Clips to the start or end if out of range.
bs (object) – The bits to insert. This can be anything promotable to
Tibs.
- Returns:
A new Tibs.
>>> Tibs('0b1011').inserted(2, '0b00') Tibs('0b100011')
- intersects(other)#
Return whether any bit is set in both this Tibs and another.
Equivalent to
(self & other).any(), but stops at the first bit set in both instead of building the intermediateTibs.- Parameters:
other (object) – The other bits. This can be anything promotable to
Tibs.- Returns:
Trueif some position is set in both, otherwiseFalse.- Raises:
ValueError – if the two Tibs have differing lengths.
>>> Tibs('0b1100').intersects('0b1010') True >>> Tibs('0b1100').intersects('0b0011') False
- inverted(pos=None)#
Return a new Tibs with selected bits inverted.
This is the immutable equivalent of
Mutibs.invert().- Parameters:
pos (int | Iterable[int] | None) – Either a single bit position, an iterable of bit positions, or None to invert every bit. Defaults to None.
- Returns:
A new Tibs.
- Raises:
IndexError – if pos < -len(self) or pos >= len(self).
>>> Tibs('0b10110').inverted([0, 2]) Tibs('0b00010')
- is_subset_of(other)#
Return whether every bit set in this Tibs is also set in another.
Equivalent to
(self & other) == self, but stops at the first bit set here and not there.- Parameters:
other (object) – The other bits. This can be anything promotable to
Tibs.- Returns:
Trueif every position set here is set in the other, otherwiseFalse.- Raises:
ValueError – if the two Tibs have differing lengths.
>>> Tibs('0b1000').is_subset_of('0b1010') True >>> Tibs('0b1100').is_subset_of('0b1010') False
- rchunks_iter(chunk_size, count=None)#
Return a reverse iterator by cutting into Tibs chunks, starting from the end.
- Parameters:
chunk_size (int) – The size in bits of the chunks to generate.
count (int | None) – If specified, at most count items are generated. Default is to cut as many times as possible.
- Returns:
A generator yielding Tibs chunks.
>>> list(Tibs('0b1100111').rchunks_iter(3)) [Tibs('0b111'), Tibs('0b100'), Tibs('0b11')]
- replaced(old, new, start=None, end=None, count=None, byte_aligned=False, mask=None)#
Search and replace and return a new Tibs.
This is the immutable equivalent of
Mutibs.replace().- Parameters:
old (object) – The bits to search for. This can be anything promotable to
Tibs.new (object) – The bits to replace with. This can be anything promotable to
Tibs.start (int | None) – The starting bit position. Defaults to 0.
end (int | None) – The end position. Defaults to len(self).
count (int | None) – If present, the maximum number of replacements to make.
byte_aligned (bool) – If
True, the bits will only be found on byte boundaries.mask (object | None) – If present, only the bits set in the mask need to match. Defaults to
None.
- Returns:
A new Tibs.
- Raises:
ValueError – if old is empty, count is negative, the slice parameters are invalid or the mask length doesn’t match the length of old.
The
maskaffects only which bits have to match; the whole of each match is still replaced bynew.>>> Tibs('0b00010010').replaced([0, 1], [1, 1, 1]) Tibs('0b0011101110') >>> Tibs('0x1f2e3f').replaced('0x0f', '0x00', mask='0x0f', byte_aligned=True) Tibs('0x002e00')
- reversed()#
Return a new instance with the bits reversed.
- Returns:
Tibs
>>> a = Tibs('0b00011') >>> a.reversed() Tibs('0b11000')
- rfind(needle, start=None, end=None, byte_aligned=False, mask=None)#
Find last occurrence of a bit sequence.
Returns the bit position if found, or None if not found.
- Parameters:
needle (object) – The bit sequence to find. This can be anything promotable to
Tibs.start (int | None) – The starting bit position. Defaults to 0.
end (int | None) – The end position. Defaults to len(self).
byte_aligned (bool) – If
True, the Tibs will only be found on byte boundaries.mask (object | None) – If present, only the bits set in the mask need to match. Defaults to
None.
- Returns:
The bit position if found, or None if not found.
- Raises:
ValueError – if
needleis empty, if the slice parameters are invalid, or if the mask length doesn’t match the needle length.
>>> Tibs('0b10111011').rfind('0b11') 6 >>> Tibs('0b10111011').rfind('0b00', mask='0b10') 5
- rfind_all_iter(needle, start=None, end=None, byte_aligned=False, mask=None)#
Find all occurrences of a bit sequence in reverse, returning an iterator of bit positions.
- Parameters:
needle (object) – The bit sequence to find. This can be anything promotable to
Tibs.start (int | None) – The starting bit position of the slice to search. Defaults to 0.
end (int | None) – The end bit position of the slice to search. Defaults to len(self).
byte_aligned (bool) – If
True, the Tibs will only be found on byte boundaries. Defaults toFalse.mask (object | None) – If present, only the bits set in the mask need to match. Defaults to
None.
- Returns:
A generator yielding bit positions.
- Raises:
ValueError – if needle is empty, if start or end are out of range, if end is before start or if the mask length doesn’t match the needle length.
All occurrences of needle are found, even if they overlap.
Note that this method is not available for
Mutibsas its value could change while the generator is still active. For that case, convert to aTibsfirst withMutibs.to_tibs(), or useMutibs.as_tibs()if you no longer need the mutable object.>>> list(Tibs('0b10111011').rfind_all_iter('0b11')) [6, 3, 2]
- rotated_left(n, start=None, end=None)#
Return a new Tibs with the bits rotated to the left.
This is the immutable equivalent of
Mutibs.rotate_left().- Parameters:
n (int) – The number of bits to rotate by.
start (int | None) – Start of slice to rotate. Defaults to 0.
end (int | None) – End of slice to rotate. Defaults to len(self).
- Returns:
A new Tibs.
- Raises:
ValueError – if n < 0.
>>> Tibs('0b10110').rotated_left(2) Tibs('0b11010')
- rotated_right(n, start=None, end=None)#
Return a new Tibs with the bits rotated to the right.
This is the immutable equivalent of
Mutibs.rotate_right().- Parameters:
n (int) – The number of bits to rotate by.
start (int | None) – Start of slice to rotate. Defaults to 0.
end (int | None) – End of slice to rotate. Defaults to len(self).
- Returns:
A new Tibs.
- Raises:
ValueError – if n < 0.
>>> Tibs('0b10110').rotated_right(1) Tibs('0b01011')
- set_at(pos)#
Return a new Tibs with one or many bits set to 1.
This is the immutable equivalent of
Mutibs.set().- Parameters:
pos (int | Iterable[int]) – Either a single bit position or an iterable of bit positions.
- Returns:
A new Tibs.
- Raises:
IndexError – if pos < -len(self) or pos >= len(self).
>>> Tibs.from_zeros(5).set_at([1, 3]) Tibs('0b01010')
- split_at(pos, /)#
Split at one or more bit positions.
posmay be a single integer or an iterable of integers. Negative positions count from the end. Positions must be in nondecreasing order after normalization, and each position must be in the range0throughlen(self), inclusive.The returned pieces are normal
Tibsslices. They share storage with the originalTibswhen possible.- Parameters:
pos (int | Iterable[int]) – The bit position or positions where the split should occur.
- Returns:
A tuple of
Tibspieces.
>>> Tibs('0b101100').split_at(3) (Tibs('0b101'), Tibs('0b100')) >>> Tibs('0b101100').split_at([2, 5]) (Tibs('0b10'), Tibs('0b110'), Tibs('0b0'))
- starts_with(prefix)#
Return whether the current Tibs starts with prefix.
- Parameters:
prefix (object) – The bits to search for. This can be anything promotable to
Tibs.- Returns:
True if the Tibs starts with the prefix, otherwise False.
>>> Tibs('0b101100').starts_with('0b101') True >>> Tibs('0b101100').starts_with('0b100') False
- to_bin(start=None, end=None)#
Return the binary representation of the Tibs as a string.
Equivalent to using the
binproperty when called with no parameters.- Parameters:
start (int | None) – Start bit position. Defaults to 0.
end (int | None) – End bit position. Defaults to len(self).
- Returns:
The binary representation.
- to_bools(start=None, end=None)#
Return the bits as a list of bools.
This is much faster than using
list()on the Tibs, which iterates bit by bit.- Parameters:
start (int | None) – Start bit position. Defaults to 0.
end (int | None) – End bit position. Defaults to len(self).
- Returns:
A list of bools.
>>> Tibs('0b101').to_bools() [True, False, True]
- to_bytes(start=None, end=None)#
Return the Tibs as a bytes object.
- Parameters:
start (int | None) – Start bit position. Defaults to 0.
end (int | None) – End bit position. Defaults to len(self).
- Returns:
The bytes representation.
- Raises:
ValueError – if the length is not a multiple of 8.
- to_f(start=None, end=None)#
Return the floating point representation of the Tibs.
The length must be 16, 32 or 64.
- Parameters:
start (int | None) – Start bit position. Defaults to 0.
end (int | None) – End bit position. Defaults to len(self).
- Returns:
The value as a Python float.
>>> Tibs('0x3fc00000').to_f() 1.5
- to_hex(start=None, end=None)#
Return the hexadecimal representation of the Tibs as a string.
Equivalent to using the
hexproperty when called with no parameters.- Parameters:
start (int | None) – Start bit position. Defaults to 0.
end (int | None) – End bit position. Defaults to len(self).
- Returns:
The hexadecimal representation.
- Raises:
ValueError – if the length is not a multiple of 4.
- to_i(start=None, end=None)#
Return the signed integer representation of the Tibs.
- Parameters:
start (int | None) – Start bit position. Defaults to 0.
end (int | None) – End bit position. Defaults to len(self).
- Returns:
The value as a signed integer.
>>> Tibs('0xe').to_i() -2
- to_mutibs()#
Create and return a mutable copy of the Tibs as a Mutibs instance.
- Returns:
A new Mutibs with the same bit data.
>>> t = Tibs.from_hex('abc') >>> m = t.to_mutibs() >>> m *= 4 >>> print(t.hex) abc >>> print(m.hex) abcabcabcabc
- to_oct(start=None, end=None)#
Return the octal representation of the Tibs as a string.
Equivalent to using the
octproperty when called with no parameters.- Parameters:
start (int | None) – Start bit position. Defaults to 0.
end (int | None) – End bit position. Defaults to len(self).
- Returns:
The octal representation.
- Raises:
ValueError – if the length is not a multiple of 3.
- to_padded_bytes(start=None, end=None)#
Return the Tibs as a bytes object, padding the right-hand side with zero bits.
This appends 0 to 7 zero bits to the end of the selected bit sequence so the returned value has a whole number of bytes. If the selected length is already a multiple of 8, this is equivalent to
to_bytes().- Parameters:
start (int | None) – Start bit position. Defaults to 0.
end (int | None) – End bit position. Defaults to len(self).
- Returns:
The padded bytes representation.
- to_raw_data()#
Return a copy of the raw byte information.
This returns the underlying byte data and can contain leading and trailing bits that are not considered part of the object’s data. Usually using
to_bytes()is what you really need.- Returns:
A tuple of the raw bytes, the bit offset and the bit length.
raw_bytes, offset, length = t.to_raw_data() assert t == Tibs.from_bytes(raw_bytes, offset=offset, length=length)
- to_u(start=None, end=None)#
Return the unsigned integer representation of the Tibs.
- Parameters:
start (int | None) – Start bit position. Defaults to 0.
end (int | None) – End bit position. Defaults to len(self).
- Returns:
The value as an unsigned integer.
>>> Tibs('0x0f').to_u() 15
- to_value(dtype, start=None, end=None)#
Return one value decoded with a dtype.
The selected range must have exactly the dtype length.
- Parameters:
dtype (Dtype | str) – The value encoding to use.
start (int | None) – Start bit position. Defaults to 0.
end (int | None) – End bit position. Defaults to len(self).
- Returns:
The decoded Python value.
>>> Tibs('0x0f').to_value("u8") 15
- to_values(dtype, start=None, end=None)#
Return a list of values decoded with a dtype.
The selected range must be a whole number of dtype values.
- Parameters:
dtype (Dtype | str) – The value encoding to use for each item.
start (int | None) – Start bit position. Defaults to 0.
end (int | None) – End bit position. Defaults to len(self).
- Returns:
A list of decoded Python values.
>>> Tibs('0x010203').to_values("u8") [1, 2, 3]
- to_values_iter(dtype, start=None, end=None)#
Return an iterator over values decoded with a dtype.
The selected range must be a whole number of dtype values.
- Parameters:
dtype (Dtype | str) – The value encoding to use for each yielded item.
start (int | None) – Start bit position. Defaults to 0.
end (int | None) – End bit position. Defaults to len(self).
- Returns:
An iterator yielding decoded Python values.
>>> list(Tibs('0x010203').to_values_iter("u8")) [1, 2, 3]
- unset_at(pos)#
Return a new Tibs with one or many bits set to 0.
This is the immutable equivalent of
Mutibs.unset().- Parameters:
pos (int | Iterable[int]) – Either a single bit position or an iterable of bit positions.
- Returns:
A new Tibs.
- Raises:
IndexError – if pos < -len(self) or pos >= len(self).
>>> Tibs.from_ones(5).unset_at([1, 3]) Tibs('0b10101')
- view(byte_order=None, bit_order=None)#
Return a view with interpretation settings.
A view does not change the underlying bits. It changes how operations such as integer conversion, byte conversion and field extraction interpret those bits.
Byte-oriented views must have a whole-byte length. This applies when using little-endian or big-endian byte order, or when using
BitOrder.Lsb0.- Parameters:
- Returns:
A new
View.
>>> Tibs('0x0100').view(byte_order=ByteOrder.Little).u 1
- be#
Return a big-endian byte-order view.
Equivalent to
view(byte_order=ByteOrder.Big).The
Tibslength must be a whole number of bytes.
- bin#
Read-only property of the binary representation of the Tibs.
Equivalent to using
to_bin()with no parameters.- Returns:
The binary representation.
- bytes#
Read-only property of the
bytesrepresentation of the Tibs.Equivalent to using
to_bytes()with no parameters.- Returns:
The bytes representation.
- Raises:
ValueError – if the length is not a multiple of 8.
- f#
Read-only property of the floating point representation of the Tibs.
Equivalent to using
to_f()with no parameters.- Returns:
The value as a Python float.
- hex#
Read-only property of the hexadecimal representation of the Tibs.
Equivalent to using
to_hex()with no parameters.- Returns:
The hexadecimal representation.
- Raises:
ValueError – if the length is not a multiple of 4.
- i#
Read-only property of the signed integer representation of the Tibs.
Equivalent to using
to_i()with no parameters.- Returns:
The value as a signed integer.
- le#
Return a little-endian byte-order view.
Equivalent to
view(byte_order=ByteOrder.Little).The
Tibslength must be a whole number of bytes.
- lsb0#
Return an LSB0 bit-order view.
BitOrder.Lsb0means that field labels are counted from the least significant bit of each byte. TheTibslength must be a whole number of bytes.Equivalent to
view(bit_order=BitOrder.Lsb0).
- msb0#
Return an MSB0 bit-order view.
BitOrder.Msb0means that field labels are counted from the most significant bit of each byte. This is the default bit order.Equivalent to
view(bit_order=BitOrder.Msb0).