-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbits.py
More file actions
1233 lines (977 loc) · 47.2 KB
/
bits.py
File metadata and controls
1233 lines (977 loc) · 47.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import numbers
import pathlib
import sys
import mmap
import struct
import array
import io
from collections import abc
import functools
from typing import Tuple, Union, List, Iterable, Any, Optional, BinaryIO, TextIO, overload, Iterator, Type, TypeVar
import bitarray
import bitarray.util
import bitstring
from bitstring.bitstore import BitStore
from bitstring import bitstore_helpers, utils
from bitstring.dtypes import Dtype, dtype_register
from bitstring.fp8 import p4binary_fmt, p3binary_fmt
from bitstring.mxfp import e3m2mxfp_fmt, e2m3mxfp_fmt, e2m1mxfp_fmt, e4m3mxfp_saturate_fmt, e5m2mxfp_saturate_fmt
from bitstring.bitstring_options import Colour
BitsType = Union['Bits', str, Iterable[Any], bool, BinaryIO, bytearray, bytes, memoryview, bitarray.bitarray]
TBits = TypeVar('TBits', bound='Bits')
MAX_CHARS: int = 250
class Bits:
"""A container holding an immutable sequence of bits.
For a mutable container use the BitArray class instead.
Methods:
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.
copy() - Return a copy of the bitstring.
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.
fromstring() -- Create a bitstring from a formatted string.
join() -- Join bitstrings together using current bitstring.
pp() -- Pretty print the 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.
tobitarray() -- Return bitstring as a bitarray from the bitarray package.
tobytes() -- Return bitstring as bytes, padding if needed.
tofile() -- Write bitstring to file, padding if needed.
unpack() -- Interpret bits using format string.
Special methods:
Also available are the operators [], ==, !=, +, *, ~, <<, >>, &, |, ^.
Properties:
[GENERATED_PROPERTY_DESCRIPTIONS]
len -- Length of the bitstring in bits.
"""
__slots__ = ('_bitstore', '_filename')
def __init__(self, auto: Optional[Union[BitsType, int]]=None, /, length: Optional[int]=None, offset: Optional[int]=None, **kwargs) -> None:
"""Either specify an 'auto' initialiser:
A string of comma separated tokens, an integer, a file object,
a bytearray, a boolean iterable, an array or another bitstring.
Or initialise via **kwargs with one (and only one) of:
bin -- binary string representation, e.g. '0b001010'.
hex -- hexadecimal string representation, e.g. '0x2ef'
oct -- octal string representation, e.g. '0o777'.
bytes -- raw data as a bytes object, for example read from a binary file.
int -- a signed integer.
uint -- an unsigned integer.
float / floatbe -- a big-endian floating point number.
bool -- a boolean (True or False).
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.
floatle -- a little-endian floating point number.
floatne -- a native-endian floating point number.
bfloat / bfloatbe - a big-endian bfloat format 16-bit floating point number.
bfloatle -- a little-endian bfloat format 16-bit floating point number.
bfloatne -- a native-endian bfloat format 16-bit floating point number.
intbe -- a signed big-endian whole byte integer.
intle -- a signed little-endian whole byte integer.
intne -- a signed native-endian whole byte integer.
uintbe -- an unsigned big-endian whole byte integer.
uintle -- an unsigned little-endian whole byte integer.
uintne -- an unsigned native-endian whole byte integer.
filename -- the path of 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 mainly intended for use when
initialising using 'bytes' or 'filename'.
"""
self._bitstore.immutable = True
def __new__(cls: Type[TBits], auto: Optional[Union[BitsType, int]]=None, /, length: Optional[int]=None, offset: Optional[int]=None, pos: Optional[int]=None, **kwargs) -> TBits:
x = super().__new__(cls)
if auto is None and (not kwargs):
if length is not None:
x._bitstore = BitStore(length)
x._bitstore.setall(0)
else:
x._bitstore = BitStore()
return x
x._initialise(auto, length, offset, **kwargs)
return x
def __getattr__(self, attribute: str) -> Any:
try:
d = Dtype(attribute)
except ValueError:
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{attribute}'.")
if d.bitlength is not None and len(self) != d.bitlength:
raise ValueError(f"bitstring length {len(self)} doesn't match length {d.bitlength} of property '{attribute}'.")
return d.get_fn(self)
def __iter__(self) -> Iterable[bool]:
return iter(self._bitstore)
def __copy__(self: TBits) -> TBits:
"""Return a new copy of the Bits for the copy module."""
return self
def __lt__(self, other: Any) -> bool:
return NotImplemented
def __gt__(self, other: Any) -> bool:
return NotImplemented
def __le__(self, other: Any) -> bool:
return NotImplemented
def __ge__(self, other: Any) -> bool:
return NotImplemented
def __add__(self: TBits, bs: BitsType) -> TBits:
"""Concatenate bitstrings and return new bitstring.
bs -- the bitstring to append.
"""
bs = self.__class__._create_from_bitstype(bs)
s = self._copy() if len(bs) <= len(self) else bs._copy()
if len(bs) <= len(self):
s._addright(bs)
else:
s._addleft(self)
return s
def __radd__(self: TBits, bs: BitsType) -> TBits:
"""Append current bitstring to bs and return new bitstring.
bs -- An object that can be 'auto' initialised as a bitstring that will be appended to.
"""
bs = self.__class__._create_from_bitstype(bs)
return bs.__add__(self)
@overload
def __getitem__(self: TBits, key: slice, /) -> TBits:
...
@overload
def __getitem__(self, key: int, /) -> bool:
...
def __getitem__(self: TBits, key: Union[slice, int], /) -> Union[TBits, bool]:
"""Return a new bitstring representing a slice of the current bitstring.
Indices are in units of the step parameter (default 1 bit).
Stepping is used to specify the number of bits in each item.
>>> print(BitArray('0b00110')[1:4])
'0b011'
>>> print(BitArray('0x00112233')[1:3:8])
'0x1122'
"""
if isinstance(key, numbers.Integral):
return bool(self._bitstore.getindex(key))
bs = super().__new__(self.__class__)
bs._bitstore = self._bitstore.getslice_withstep(key)
return bs
def __len__(self) -> int:
"""Return the length of the bitstring in bits."""
return self._getlength()
def __bytes__(self) -> bytes:
return self.tobytes()
def __str__(self) -> str:
"""Return approximate string representation of bitstring for printing.
Short strings will be given wholly in hexadecimal or binary. Longer
strings may be part hexadecimal and part binary. Very long strings will
be truncated with '...'.
"""
length = len(self)
if not length:
return ''
if length > MAX_CHARS * 4:
return ''.join(('0x', self[0:MAX_CHARS * 4]._gethex(), '...'))
if length < 32 and length % 4 != 0:
return '0b' + self.bin
if not length % 4:
return '0x' + self.hex
bits_at_end = length % 4
return ''.join(('0x', self[0:length - bits_at_end]._gethex(), ', ', '0b', self[length - bits_at_end:]._getbin()))
def __repr__(self) -> str:
"""Return representation that could be used to recreate the bitstring.
If the returned string is too long it will be truncated. See __str__().
"""
return self._repr(self.__class__.__name__, len(self), 0)
def __eq__(self, bs: Any, /) -> bool:
"""Return True if two bitstrings have the same binary representation.
>>> BitArray('0b1110') == '0xe'
True
"""
try:
return self._bitstore == Bits._create_from_bitstype(bs)._bitstore
except TypeError:
return False
def __ne__(self, bs: Any, /) -> bool:
"""Return False if two bitstrings have the same binary representation.
>>> BitArray('0b111') == '0x7'
False
"""
return not self.__eq__(bs)
def __invert__(self: TBits) -> TBits:
"""Return bitstring with every bit inverted.
Raises Error if the bitstring is empty.
"""
if len(self) == 0:
raise bitstring.Error('Cannot invert empty bitstring.')
s = self._copy()
s._invert_all()
return s
def __lshift__(self: TBits, n: int, /) -> TBits:
"""Return bitstring with bits shifted by n to the left.
n -- the number of bits to shift. Must be >= 0.
"""
if n < 0:
raise ValueError('Cannot shift by a negative amount.')
if len(self) == 0:
raise ValueError('Cannot shift an empty bitstring.')
n = min(n, len(self))
s = self._absolute_slice(n, len(self))
s._addright(Bits(n))
return s
def __rshift__(self: TBits, n: int, /) -> TBits:
"""Return bitstring with bits shifted by n to the right.
n -- the number of bits to shift. Must be >= 0.
"""
if n < 0:
raise ValueError('Cannot shift by a negative amount.')
if len(self) == 0:
raise ValueError('Cannot shift an empty bitstring.')
if not n:
return self._copy()
s = self.__class__(length=min(n, len(self)))
n = min(n, len(self))
s._addright(self._absolute_slice(0, len(self) - n))
return s
def __mul__(self: TBits, n: int, /) -> TBits:
"""Return bitstring consisting of n concatenations of self.
Called for expression of the form 'a = b*3'.
n -- The number of concatenations. Must be >= 0.
"""
if n < 0:
raise ValueError('Cannot multiply by a negative integer.')
if not n:
return self.__class__()
s = self._copy()
s._imul(n)
return s
def __rmul__(self: TBits, n: int, /) -> TBits:
"""Return bitstring consisting of n concatenations of self.
Called for expressions of the form 'a = 3*b'.
n -- The number of concatenations. Must be >= 0.
"""
return self.__mul__(n)
def __and__(self: TBits, bs: BitsType, /) -> TBits:
"""Bit-wise 'and' between two bitstrings. Returns new bitstring.
bs -- The bitstring to '&' with.
Raises ValueError if the two bitstrings have differing lengths.
"""
if bs is self:
return self.copy()
bs = Bits._create_from_bitstype(bs)
s = object.__new__(self.__class__)
s._bitstore = self._bitstore & bs._bitstore
return s
def __rand__(self: TBits, bs: BitsType, /) -> TBits:
"""Bit-wise 'and' between two bitstrings. Returns new bitstring.
bs -- the bitstring to '&' with.
Raises ValueError if the two bitstrings have differing lengths.
"""
return self.__and__(bs)
def __or__(self: TBits, bs: BitsType, /) -> TBits:
"""Bit-wise 'or' between two bitstrings. Returns new bitstring.
bs -- The bitstring to '|' with.
Raises ValueError if the two bitstrings have differing lengths.
"""
if bs is self:
return self.copy()
bs = Bits._create_from_bitstype(bs)
s = object.__new__(self.__class__)
s._bitstore = self._bitstore | bs._bitstore
return s
def __ror__(self: TBits, bs: BitsType, /) -> TBits:
"""Bit-wise 'or' between two bitstrings. Returns new bitstring.
bs -- The bitstring to '|' with.
Raises ValueError if the two bitstrings have differing lengths.
"""
return self.__or__(bs)
def __xor__(self: TBits, bs: BitsType, /) -> TBits:
"""Bit-wise 'xor' between two bitstrings. Returns new bitstring.
bs -- The bitstring to '^' with.
Raises ValueError if the two bitstrings have differing lengths.
"""
bs = Bits._create_from_bitstype(bs)
s = object.__new__(self.__class__)
s._bitstore = self._bitstore ^ bs._bitstore
return s
def __rxor__(self: TBits, bs: BitsType, /) -> TBits:
"""Bit-wise 'xor' between two bitstrings. Returns new bitstring.
bs -- The bitstring to '^' with.
Raises ValueError if the two bitstrings have differing lengths.
"""
return self.__xor__(bs)
def __contains__(self, bs: BitsType, /) -> bool:
"""Return whether bs is contained in the current bitstring.
bs -- The bitstring to search for.
"""
found = Bits.find(self, bs, bytealigned=False)
return bool(found)
def __hash__(self) -> int:
"""Return an integer hash of the object."""
if len(self) <= 2000:
return hash((self.tobytes(), len(self)))
else:
return hash(((self[:800] + self[-800:]).tobytes(), len(self)))
def __bool__(self) -> bool:
"""Return False if bitstring is empty, otherwise return True."""
return len(self) != 0
def _clear(self) -> None:
"""Reset the bitstring to an empty state."""
pass
def _setauto_no_length_or_offset(self, s: BitsType, /) -> None:
"""Set bitstring from a bitstring, file, bool, array, iterable or string."""
pass
def _setauto(self, s: BitsType, length: Optional[int], offset: Optional[int], /) -> None:
"""Set bitstring from a bitstring, file, bool, array, iterable or string."""
pass
def _setfile(self, filename: str, length: Optional[int]=None, offset: Optional[int]=None) -> None:
"""Use file as source of bits."""
pass
def _setbytes(self, data: Union[bytearray, bytes, List], length: None=None) -> None:
"""Set the data from a bytes or bytearray object."""
pass
def _setbytes_with_truncation(self, data: Union[bytearray, bytes], length: Optional[int]=None, offset: Optional[int]=None) -> None:
"""Set the data from a bytes or bytearray object, with optional offset and length truncations."""
pass
def _getbytes(self) -> bytes:
"""Return the data as an ordinary bytes object."""
pass
_unprintable = list(range(0, 32))
_unprintable.extend(range(127, 255))
def _getbytes_printable(self) -> str:
"""Return an approximation of the data as a string of printable characters."""
pass
def _setuint(self, uint: int, length: Optional[int]=None) -> None:
"""Reset the bitstring to have given unsigned int interpretation."""
pass
def _setuintle(self, uint: int, length: Optional[int]=None) -> None:
"""Reset the bitstring to have given unsigned int interpretation in little-endian."""
if length is None:
# Calculate the minimum number of bits needed
length = max(uint.bit_length(), 1)
if length % 8:
length += 8 - (length % 8)
if length % 8:
raise ValueError("Little-endian integers must be whole-byte. Length = {0} bits.".format(length))
if uint < 0:
raise ValueError("Little-endian unsigned integer cannot be negative.")
if uint >= (1 << length):
raise ValueError("Little-endian unsigned integer is too large for length {0}.".format(length))
# Convert to bytes in little-endian order
num_bytes = length // 8
byte_data = uint.to_bytes(num_bytes, byteorder='little', signed=False)
self._setbytes(byte_data)
def _setintle(self, value: int, length: Optional[int]=None) -> None:
"""Reset the bitstring to have given signed int interpretation in little-endian."""
if length is None:
# Calculate the minimum number of bits needed
length = max(value.bit_length() + 1, 1) # +1 for sign bit
if length % 8:
length += 8 - (length % 8)
if length % 8:
raise ValueError("Little-endian integers must be whole-byte. Length = {0} bits.".format(length))
num_bytes = length // 8
try:
byte_data = value.to_bytes(num_bytes, byteorder='little', signed=True)
except OverflowError:
raise ValueError("Little-endian signed integer is too large for length {0}.".format(length))
self._setbytes(byte_data)
def _setfloatbe(self, value: float, length: Optional[int]=None) -> None:
"""Reset the bitstring to have given float interpretation in big-endian."""
if length is None:
raise ValueError("A length must be specified with float initialisation.")
if length == 16:
fmt = '>e'
elif length == 32:
fmt = '>f'
elif length == 64:
fmt = '>d'
else:
raise ValueError("float length must be 16, 32 or 64 bits.")
try:
byte_data = struct.pack(fmt, value)
except (struct.error, OverflowError):
raise ValueError("Float is too large for length {0}.".format(length))
self._setbytes(byte_data)
def _setfloatle(self, value: float, length: Optional[int]=None) -> None:
"""Reset the bitstring to have given float interpretation in little-endian."""
if length is None:
raise ValueError("A length must be specified with float initialisation.")
if length == 16:
fmt = '<e'
elif length == 32:
fmt = '<f'
elif length == 64:
fmt = '<d'
else:
raise ValueError("float length must be 16, 32 or 64 bits.")
try:
byte_data = struct.pack(fmt, value)
except (struct.error, OverflowError):
raise ValueError("Float is too large for length {0}.".format(length))
self._setbytes(byte_data)
def _setbfloatbe(self, value: float, length: Optional[int]=None) -> None:
"""Reset the bitstring to have given bfloat interpretation in big-endian."""
if length is not None and length != 16:
raise ValueError("bfloat must be 16 bits.")
# Convert to 32-bit float first
try:
byte_data = struct.pack('>f', value)
# Take only the first two bytes (16 bits) for bfloat
self._setbytes(byte_data[:2])
except (struct.error, OverflowError):
raise ValueError("Float is too large for bfloat format.")
def _getbfloatbe(self) -> float:
"""Return data as a bfloat in big-endian format."""
if len(self) != 16:
raise bitstring.InterpretError("bfloat requires 16 bits.")
# Convert to 32-bit float by appending two zero bytes
byte_data = self._getbytes() + b'\x00\x00'
try:
return struct.unpack('>f', byte_data)[0]
except struct.error:
raise bitstring.InterpretError("Cannot interpret as bfloat.")
def _setbfloatle(self, value: float, length: Optional[int]=None) -> None:
"""Reset the bitstring to have given bfloat interpretation in little-endian."""
if length is not None and length != 16:
raise ValueError("bfloat must be 16 bits.")
# Convert to 32-bit float first
try:
byte_data = struct.pack('<f', value)
# Take only the last two bytes (16 bits) for bfloat
self._setbytes(byte_data[2:])
except (struct.error, OverflowError):
raise ValueError("Float is too large for bfloat format.")
def _getbfloatle(self) -> float:
"""Return data as a bfloat in little-endian format."""
if len(self) != 16:
raise bitstring.InterpretError("bfloat requires 16 bits.")
# Convert to 32-bit float by prepending two zero bytes
byte_data = b'\x00\x00' + self._getbytes()
try:
return struct.unpack('<f', byte_data)[0]
except struct.error:
raise bitstring.InterpretError("Cannot interpret as bfloat.")
def _setbits(self, bits: Bits, length: Optional[int]=None) -> None:
"""Reset the bitstring to have given bits interpretation."""
if length is not None and len(bits) != length:
raise ValueError("Bits length {0} does not match required length {1}.".format(len(bits), length))
self._bitstore = bits._bitstore.copy()
def _getbits(self) -> Bits:
"""Return data as a Bits object."""
return self.copy()
def _setbool(self, value: bool, length: Optional[int]=None) -> None:
"""Reset the bitstring to have given bool interpretation."""
if length is not None and length != 1:
raise ValueError("Boolean values must be 1 bit long.")
self._bitstore = BitStore(1)
self._bitstore.setall(1 if value else 0)
def _getbool(self) -> bool:
"""Return data as a bool."""
if len(self) != 1:
raise bitstring.InterpretError("Cannot interpret as bool: length must be 1 bit.")
return bool(self._bitstore.getindex(0))
def _setse(self, value: int, length: Optional[int]=None) -> None:
"""Reset the bitstring to have given signed exponential-Golomb code interpretation."""
if length is not None:
raise ValueError("Length cannot be specified for signed exponential-Golomb codes.")
# Convert to unsigned by mapping negative values to positive ones
unsigned = (abs(value) << 1) - (1 if value > 0 else 0)
# Get the number of bits needed for the unsigned value
num_bits = unsigned.bit_length()
# Add leading zeros and the code
self._bitstore = BitStore(num_bits * 2 + 1)
self._bitstore.setall(0)
# Set the code bits
for i in range(num_bits):
self._bitstore.setindex(num_bits + i, (unsigned >> (num_bits - 1 - i)) & 1)
def _getse(self) -> int:
"""Return data as a signed exponential-Golomb code."""
# Find the first 1 bit
for i in range(len(self)):
if self._bitstore.getindex(i):
# Get the code bits
code_bits = 0
for j in range(i + 1, min(2 * i + 1, len(self))):
code_bits = (code_bits << 1) | self._bitstore.getindex(j)
# Convert back to signed value
unsigned = code_bits + (1 << i)
# Map back to signed value
return (unsigned + 1) >> 1 if unsigned & 1 else -(unsigned >> 1)
raise bitstring.InterpretError("Cannot find any 1 bits in exponential-Golomb code.")
def _setue(self, value: int, length: Optional[int]=None) -> None:
"""Reset the bitstring to have given unsigned exponential-Golomb code interpretation."""
if length is not None:
raise ValueError("Length cannot be specified for unsigned exponential-Golomb codes.")
if value < 0:
raise ValueError("Unsigned exponential-Golomb codes cannot be negative.")
# Get the number of bits needed for the value + 1
num_bits = (value + 1).bit_length()
# Add leading zeros and the code
self._bitstore = BitStore(num_bits * 2)
self._bitstore.setall(0)
# Set the code bits
for i in range(num_bits - 1):
self._bitstore.setindex(num_bits - 1 + i, (value >> (num_bits - 2 - i)) & 1)
# Set the terminating 1 bit
self._bitstore.setindex(num_bits - 1, 1)
def _getue(self) -> int:
"""Return data as an unsigned exponential-Golomb code."""
# Find the first 1 bit
for i in range(len(self)):
if self._bitstore.getindex(i):
# Get the code bits
code_bits = 0
for j in range(i + 1, min(2 * i + 1, len(self))):
code_bits = (code_bits << 1) | self._bitstore.getindex(j)
# Convert back to unsigned value
return code_bits + (1 << i) - 1
raise bitstring.InterpretError("Cannot find any 1 bits in exponential-Golomb code.")
def _setsie(self, value: int, length: Optional[int]=None) -> None:
"""Reset the bitstring to have given signed interleaved exponential-Golomb code interpretation."""
if length is not None:
raise ValueError("Length cannot be specified for signed interleaved exponential-Golomb codes.")
# Convert to unsigned by mapping negative values to positive ones
unsigned = abs(value) << 1
if value < 0:
unsigned -= 1
# Get the number of bits needed for the unsigned value
num_bits = unsigned.bit_length()
# Add leading zeros and the code
self._bitstore = BitStore(num_bits * 2)
self._bitstore.setall(0)
# Set the code bits
for i in range(num_bits - 1):
self._bitstore.setindex(num_bits - 1 + i, (unsigned >> (num_bits - 2 - i)) & 1)
# Set the terminating 1 bit
self._bitstore.setindex(num_bits - 1, 1)
def _getsie(self) -> int:
"""Return data as a signed interleaved exponential-Golomb code."""
# Find the first 1 bit
for i in range(len(self)):
if self._bitstore.getindex(i):
# Get the code bits
code_bits = 0
for j in range(i + 1, min(2 * i + 1, len(self))):
code_bits = (code_bits << 1) | self._bitstore.getindex(j)
# Convert back to unsigned value
unsigned = code_bits + (1 << i) - 1
# Map back to signed value
return -(unsigned >> 1) - 1 if unsigned & 1 else unsigned >> 1
raise bitstring.InterpretError("Cannot find any 1 bits in exponential-Golomb code.")
def _setuie(self, value: int, length: Optional[int]=None) -> None:
"""Reset the bitstring to have given unsigned interleaved exponential-Golomb code interpretation."""
if length is not None:
raise ValueError("Length cannot be specified for unsigned interleaved exponential-Golomb codes.")
if value < 0:
raise ValueError("Unsigned interleaved exponential-Golomb codes cannot be negative.")
# Get the number of bits needed for the value + 1
num_bits = (value + 1).bit_length()
# Add leading zeros and the code
self._bitstore = BitStore(num_bits * 2)
self._bitstore.setall(0)
# Set the code bits
for i in range(num_bits - 1):
self._bitstore.setindex(num_bits - 1 + i, (value >> (num_bits - 2 - i)) & 1)
# Set the terminating 1 bit
self._bitstore.setindex(num_bits - 1, 1)
def _getuie(self) -> int:
"""Return data as an unsigned interleaved exponential-Golomb code."""
# Find the first 1 bit
for i in range(len(self)):
if self._bitstore.getindex(i):
# Get the code bits
code_bits = 0
for j in range(i + 1, min(2 * i + 1, len(self))):
code_bits = (code_bits << 1) | self._bitstore.getindex(j)
# Convert back to unsigned value
return code_bits + (1 << i) - 1
raise bitstring.InterpretError("Cannot find any 1 bits in exponential-Golomb code.")
def _setpad(self, value: None, length: Optional[int]=None) -> None:
"""Reset the bitstring to have given padding bits interpretation."""
if length is None:
raise ValueError("Length must be specified for padding bits.")
if value is not None:
raise ValueError("Padding bits cannot have a value.")
self._bitstore = BitStore(length)
self._bitstore.setall(0)
def _getpad(self) -> None:
"""Return data as padding bits (always returns None)."""
return None
def _setp3binary(self, value: float, length: Optional[int]=None) -> None:
"""Reset the bitstring to have given p3binary float interpretation."""
if length is not None and length != 8:
raise ValueError("p3binary must be 8 bits.")
# Convert to bytes using the p3binary format
byte_data = p3binary_fmt.float_to_int8(value).to_bytes(1, byteorder='big', signed=False)
self._setbytes(byte_data)
def _getp3binary(self) -> float:
"""Return data as a p3binary float."""
if len(self) != 8:
raise bitstring.InterpretError("p3binary requires 8 bits.")
# Convert from bytes using the p3binary format
byte_data = self._getbytes()
return p3binary_fmt.lut_binary8_to_float[byte_data[0]]
def _setp4binary(self, value: float, length: Optional[int]=None) -> None:
"""Reset the bitstring to have given p4binary float interpretation."""
if length is not None and length != 8:
raise ValueError("p4binary must be 8 bits.")
# Convert to bytes using the p4binary format
byte_data = p4binary_fmt.float_to_int8(value).to_bytes(1, byteorder='big', signed=False)
self._setbytes(byte_data)
def _getp4binary(self) -> float:
"""Return data as a p4binary float."""
if len(self) != 8:
raise bitstring.InterpretError("p4binary requires 8 bits.")
# Convert from bytes using the p4binary format
byte_data = self._getbytes()
return p4binary_fmt.lut_binary8_to_float[byte_data[0]]
def _sete4m3mxfp(self, value: float, length: Optional[int]=None) -> None:
"""Reset the bitstring to have given e4m3mxfp float interpretation."""
if length is not None and length != 8:
raise ValueError("e4m3mxfp must be 8 bits.")
# Convert to bytes using the e4m3mxfp format
byte_data = e4m3mxfp_fmt.float_to_int(value).to_bytes(1, byteorder='big', signed=False)
self._setbytes(byte_data)
def _gete4m3mxfp(self) -> float:
"""Return data as an e4m3mxfp float."""
if len(self) != 8:
raise bitstring.InterpretError("e4m3mxfp requires 8 bits.")
# Convert from bytes using the e4m3mxfp format
byte_data = self._getbytes()
return e4m3mxfp_fmt.lut_int_to_float[byte_data[0]]
pass
def _getuint(self) -> int:
"""Return data as an unsigned int."""
pass
def _setint(self, int_: int, length: Optional[int]=None) -> None:
"""Reset the bitstring to have given signed int interpretation."""
pass
def _getint(self) -> int:
"""Return data as a two's complement signed int."""
pass
def _setuintbe(self, uintbe: int, length: Optional[int]=None) -> None:
"""Set the bitstring to a big-endian unsigned int interpretation."""
pass
def _getuintbe(self) -> int:
"""Return data as a big-endian two's complement unsigned int."""
pass
def _setintbe(self, intbe: int, length: Optional[int]=None) -> None:
"""Set bitstring to a big-endian signed int interpretation."""
pass
def _getintbe(self) -> int:
"""Return data as a big-endian two's complement signed int."""
pass
def _getuintle(self) -> int:
"""Interpret as a little-endian unsigned int."""
pass
def _getintle(self) -> int:
"""Interpret as a little-endian signed int."""
pass
def _getfloatbe(self) -> float:
"""Interpret the whole bitstring as a big-endian float."""
pass
def _getfloatle(self) -> float:
"""Interpret the whole bitstring as a little-endian float."""
pass
def _setue(self, i: int) -> None:
"""Initialise bitstring with unsigned exponential-Golomb code for integer i.
Raises CreationError if i < 0.
"""
pass
def _readue(self, pos: int) -> Tuple[int, int]:
"""Return interpretation of next bits as unsigned exponential-Golomb code.
Raises ReadError if the end of the bitstring is encountered while
reading the code.
"""
pass
def _setse(self, i: int) -> None:
"""Initialise bitstring with signed exponential-Golomb code for integer i."""
pass
def _readse(self, pos: int) -> Tuple[int, int]:
"""Return interpretation of next bits as a signed exponential-Golomb code.
Advances position to after the read code.
Raises ReadError if the end of the bitstring is encountered while
reading the code.
"""
pass
def _setuie(self, i: int) -> None:
"""Initialise bitstring with unsigned interleaved exponential-Golomb code for integer i.
Raises CreationError if i < 0.
"""
pass
def _readuie(self, pos: int) -> Tuple[int, int]:
"""Return interpretation of next bits as unsigned interleaved exponential-Golomb code.
Raises ReadError if the end of the bitstring is encountered while
reading the code.
"""
pass
def _setsie(self, i: int) -> None:
"""Initialise bitstring with signed interleaved exponential-Golomb code for integer i."""
pass
def _readsie(self, pos: int) -> Tuple[int, int]:
"""Return interpretation of next bits as a signed interleaved exponential-Golomb code.
Advances position to after the read code.
Raises ReadError if the end of the bitstring is encountered while
reading the code.
"""
pass
def _setbin_safe(self, binstring: str, length: None=None) -> None:
"""Reset the bitstring to the value given in binstring."""
pass
def _setbin_unsafe(self, binstring: str, length: None=None) -> None:
"""Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'."""
pass
def _getbin(self) -> str:
"""Return interpretation as a binary string."""
pass
def _setoct(self, octstring: str, length: None=None) -> None:
"""Reset the bitstring to have the value given in octstring."""
pass
def _getoct(self) -> str:
"""Return interpretation as an octal string."""
pass
def _sethex(self, hexstring: str, length: None=None) -> None:
"""Reset the bitstring to have the value given in hexstring."""
pass
def _gethex(self) -> str:
"""Return the hexadecimal representation as a string.
Raises an InterpretError if the bitstring's length is not a multiple of 4.
"""
pass
def _getlength(self) -> int:
"""Return the length of the bitstring in bits."""
pass
def _copy(self: TBits) -> TBits:
"""Create and return a new copy of the Bits (always in memory)."""
pass
def _slice(self: TBits, start: int, end: int) -> TBits:
"""Used internally to get a slice, without error checking."""
pass
def _absolute_slice(self: TBits, start: int, end: int) -> TBits:
"""Used internally to get a slice, without error checking.
Uses MSB0 bit numbering even if LSB0 is set."""
pass
def _readtoken(self, name: str, pos: int, length: Optional[int]) -> Tuple[Union[float, int, str, None, Bits], int]:
"""Reads a token from the bitstring and returns the result."""
pass
def _addright(self, bs: Bits, /) -> None:
"""Add a bitstring to the RHS of the current bitstring."""
pass
def _addleft(self, bs: Bits, /) -> None:
"""Prepend a bitstring to the current bitstring."""
pass
def _truncateleft(self: TBits, bits: int, /) -> TBits:
"""Truncate bits from the start of the bitstring. Return the truncated bits."""
pass
def _truncateright(self: TBits, bits: int, /) -> TBits:
"""Truncate bits from the end of the bitstring. Return the truncated bits."""
pass
def _insert(self, bs: Bits, pos: int, /) -> None:
"""Insert bs at pos."""
pass
def _overwrite(self, bs: Bits, pos: int, /) -> None:
"""Overwrite with bs at pos."""
pass
def _delete(self, bits: int, pos: int, /) -> None:
"""Delete bits at pos."""
pass
def _reversebytes(self, start: int, end: int) -> None:
"""Reverse bytes in-place."""
pass
def _invert(self, pos: int, /) -> None:
"""Flip bit at pos 1<->0."""
pass
def _invert_all(self) -> None:
"""Invert every bit."""
pass
def _ilshift(self: TBits, n: int, /) -> TBits:
"""Shift bits by n to the left in place. Return self."""
pass
def _irshift(self: TBits, n: int, /) -> TBits:
"""Shift bits by n to the right in place. Return self."""
pass
def _imul(self: TBits, n: int, /) -> TBits:
"""Concatenate n copies of self in place. Return self."""
pass
def _validate_slice(self, start: Optional[int], end: Optional[int]) -> Tuple[int, int]:
"""Validate start and end and return them as positive bit positions."""
pass
def unpack(self, fmt: Union[str, List[Union[str, int]]], **kwargs) -> List[Union[int, float, str, Bits, bool, bytes, None]]:
"""Interpret the whole bitstring using fmt and return list.
fmt -- A single string or a list of strings with comma separated tokens
describing how to interpret the bits in the bitstring. Items
can also be integers, for reading new bitstring of the given length.
kwargs -- A dictionary or keyword-value pairs - the keywords used in the
format string will be replaced with their given value.
Raises ValueError if the format is not understood. If not enough bits