-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbinary.py
6937 lines (6282 loc) · 298 KB
/
binary.py
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
#!/usr/bin/python3
"""# Floating-point Binary Fractions: Do math in base 2!

```
████ ███
░░███ ░░░
░███████ ████ ████████ ██████ ████████ █████ ████
░███░░███░░███ ░░███░░███ ░░░░░███ ░░███░░███░░███ ░███
░███ ░███ ░███ ░███ ░███ ███████ ░███ ░░░ ░███ ░███
░███ ░███ ░███ ░███ ░███ ███░░███ ░███ ░███ ░███
████████ █████ ████ █████░░████████ █████ ░░███████
░░░░░░░░ ░░░░░ ░░░░ ░░░░░ ░░░░░░░░ ░░░░░ ░░░░░███
███ ░███
░░██████
░░░░░░
██████ ███ ███
███░░███ ░███ ░░░
░███ ░░░ ████████ ██████ ██████ ███████ ████ ██████ ████████ █████
███████ ░░███░░███ ░░░░░███ ███░░███░░░███░ ░░███ ███░░███░░███░░███ ███░░
░░░███░ ░███ ░░░ ███████ ░███ ░░░ ░███ ░███ ░███ ░███ ░███ ░███ ░░█████
░███ ░███ ███░░███ ░███ ███ ░███ ███ ░███ ░███ ░███ ░███ ░███ ░░░░███
█████ █████ ░░████████░░██████ ░░█████ █████░░██████ ████ █████ ██████
░░░░░ ░░░░░ ░░░░░░░░ ░░░░░░ ░░░░░ ░░░░░ ░░░░░░ ░░░░ ░░░░░ ░░░░░░
```
[](https://pypi.org/project/binary-fractions/)
[](https://github.com/psf/black)
[](http://mypy-lang.org/)
[](https://github.com/Jonny-exe/binary-fractions/blob/master/binary_fractions/README.md)
An implementation of a floating-point binary fractions class and module
in Python. Work with binary fractions and binary floats with ease!
This module allows one to represent integers, floats and fractions as
binary strings.
- e.g. the integer 3 will be represented as string '0b11'.
- e.g. the float -3.75 will be represented as string '-0b11.11'.
- e.g. the fraction 1/2 will be represented as string '0b0.1'
- Exponential representation is also possible:
'-0b0.01111e3', '-0b11.1e1' or '-0b1110e-2' all represent float -3.75.
- two's complement representation is possible too:
'11.11' for -1.25 in decimal, or '-0b1.01' in binary fraction.
Many operations and transformations are offered.
You can sum, subtract, multiply, and divide long floating-point binary
fractions. You can compute power of them, shift them left, shift them right,
etc.
Basic representation of binary fractions and binary floats:
A binary fraction is a subset of binary floats. Basically, a binary fraction
is a binary float without an exponent (e.g. '-0b101.0101').
Let's have a look at an example binary float value to see how it is represented.
```
prefix '0b' to indicate "binary" or "base 2"
||
|| decimal point
|| |
|| | exponent separator
|| | |
|| | | exponent in base 10 (not in base 2!)
|| | | ||
-0b101.0101e-34 <-- example floating-point binary fraction
| ||| |||| |
sign ||| |||| exponent sign
||| ||||
||| fraction bits in base 2
|||
integer bits in base 2
```
If you are curious about floating point binary fractions, have a look at:
- https://en.wikipedia.org/wiki/Computer_number_format#Representing_fractions_in_binary
- https://www.electronics-tutorials.ws/binary/binary-fractions.html
- https://ryanstutorials.net/binary-tutorial/binary-floating-point.php
- https://planetcalc.com/862/
If you are curious about Two's complement:
- https://janmr.com/blog/2010/07/bitwise-operators-and-negative-numbers/
- https://en.wikipedia.org/wiki/Two%27s_complement
## License:
- GPL v3 or later
## Features:
- Python 3
- constructors for various types: int, float, Fraction, str, TwosComplement, Binary
- supports many operators: +, -, *, /, //, %, **, <<, >>, ~, &, ...
- supports many methods: not, abs, round, floor, ceil, ...
- internally the value is kept as a Fraction and most operations are done
in Fractions. This results in better performance and infinite precision.
Only a few limited operations such as 'and', 'or', 'xor', and 'invert'
are done on strings.
- very high precision
- many operations are lossless, i.e. with no rounding errors or loss of precision
- supports very long binary fractions
- supports exponential representations
- well documented
- Please read the documentation inside the source code
([binary.py](https://github.com/Jonny-exe/binary-fractions/blob/master/binary_fractions/binary.py)).
- Or look at the pydoc-generated documentation in
[README.md](https://github.com/Jonny-exe/binary-fractions/blob/master/binary_fractions/README.md).
- well tested
- over 1600 test cases
## Sample usage, Example calls:
Please have a look at the short example program that uses the
`Binary` class and module. See file
[binary_sample.py](https://github.com/Jonny-exe/binary-fractions/blob/master/binary_fractions/binary_sample.py).
The sample source code looks like this:
```
#!/usr/bin/python3
# Sample program using the Binary class and module.
# Install with: pip3 install --upgrade binary-fractions
if __name__ == "__main__":
from binary_fractions import TwosComplement, Binary
from math import ceil, floor
bf1str: str = "-1.01" # -1.25
bf2str: str = "10.1" # 2.5
bf3str: str = "10.1e-3" # 2.5/8
tcstr1: str = "10.1" # -1.5 in two's complement, '-0b1.1' as binary fraction
tcstr2: str = "100001001000.1" # -1975.5 in two's complement, '-0b11110111000.1'
fl1: float = 2.3
fl2: float = -1975.5
bf1: Binary = Binary(bf1str)
bf2: Binary = Binary(bf2str)
bf3: Binary = Binary(bf3str)
tc1: TwosComplement = TwosComplement(tcstr1)
tc2: TwosComplement = TwosComplement(tcstr2)
tc3: TwosComplement = TwosComplement(fl2)
print("Sample program demonstrating binary fractions class and module:")
print(f"Binary({fl1}) = {Binary(fl1)}")
print(f"Binary({fl2}) = {Binary(fl2)}")
print(f"Binary({bf3str}) = {Binary(bf3str)}")
print(f"{bf1} = {bf1}")
print(f"{bf1} + {bf2} = {bf1+bf2}")
print(f"{bf1} - {bf2} = {bf1-bf2}")
print(f"{bf1} * {bf2} = {bf1*bf2}")
print(f"{bf1} / {bf2} = {bf1/bf2}")
print(f"{bf1} // {bf2} = {bf1//bf2}")
print(f"{bf1} % {bf2} = {bf1%bf2}")
print(f"{bf2} ** {bf1} = {bf2**bf1}")
print(f"{bf1} >> {1} = {bf1>>1}")
print(f"{bf1} << {1} = {bf1<<1}")
print(f"abs({bf1}) = {abs(bf1)}")
print(f"round({bf1}) = {round(bf1)}")
print(f"ceil({bf1}) = {ceil(bf1)} (int)")
print(f"Binary('{bf1}').ceil() = {bf1.ceil()} (Binary)")
print(f"floor({bf1}) = {floor(bf1)} (int)")
print(f"Binary('{bf1}').floor() = {bf1.floor()} (Binary)")
print(f"int({bf1}) = {int(bf1)}")
print(f"float({bf1}) = {float(bf1)}")
print(f"str({bf1}) = {str(bf1)}")
print(f"str({bf3}) = {str(bf3)}")
print(f"Fraction({bf1}) = {bf1.fraction}")
print(f"Binary({bf1}).fraction = {bf1.fraction}")
print(f"Binary({fl2}).string = {Binary(fl2).string}")
print(f"{bf1} & {bf2} = {bf1&bf2}")
print(f"{bf1} | {bf2} = {bf1|bf2}")
print(f"{bf1} ^ {bf2} = {bf1^bf2}")
print(f"~(floor({bf2})) = {~(floor(bf2))}")
print(f"type({bf1}) = {type(bf1)}")
print(f"type({tc1}) = {type(tc1)}")
print(f"Binary('{bf3}').to_no_exponent() = {bf3.to_no_exponent()}")
print(f"Binary('{bf3}').to_no_mantissa() = {bf3.to_no_mantissa()}")
# scientific notation
print(f"Binary('{bf3}').to_sci_exponent() = {bf3.to_sci_exponent()}")
# engineering notation
print(f"Binary('{bf3}').to_eng_exponent() = {bf3.to_eng_exponent()}")
print(f"Binary('{bf1}').to_twos_complement() = {bf1.to_twoscomplement()}")
print(f"Binary(TwosComplement('{tcstr1}')) = {Binary.from_twoscomplement(tc1)}")
print(f"Binary(TwosComplement('{tcstr2}')) = {Binary.from_twoscomplement(tc2)}")
print(f"Binary(TwosComplement({fl2})) = {Binary.from_twoscomplement(tc3)}")
print(f"TwosComplement({fl2}) = {TwosComplement(fl2)}")
print("And there are more operands, more methods, more functions, ...")
print("For more information read the documentation at:")
print("https://raw.githubusercontent.com/Jonny-exe/binary-fractions")
```
When executed with the command `python3 binary_sample.py`, it returns these
results:
```
Sample program demonstrating binary fractions class and module:
Binary(2.3) = 0b10.01001100110011001100110011001100110011001100110011
Binary(-1975.5) = -0b11110110111.1
Binary(10.1e-3) = 0b10.1e-3
-0b1.01 = -0b1.01
-0b1.01 + 0b10.1 = 0b1.01
-0b1.01 - 0b10.1 = -0b11.11
-0b1.01 * 0b10.1 = -0b11.001
-0b1.01 / 0b10.1 = -0b0.1
-0b1.01 // 0b10.1 = -0b1
-0b1.01 % 0b10.1 = 0b1.01
0b10.1 ** -0b1.01 = 0b0.010100010110111110001011100001001001101110110100110011
-0b1.01 >> 1 = -0b0.101
-0b1.01 << 1 = -0b10.1
abs(-0b1.01) = 0b1.01
round(-0b1.01) = -0b1
ceil(-0b1.01) = -1 (int)
Binary('-0b1.01').ceil() = -0b1 (Binary)
floor(-0b1.01) = -2 (int)
Binary('-0b1.01').floor() = -0b10 (Binary)
int(-0b1.01) = -1
float(-0b1.01) = -1.25
str(-0b1.01) = -0b1.01
str(0b10.1e-3) = 0b10.1e-3
Fraction(-0b1.01) = -5/4
-0b1.01 & 0b10.1 = 0b10.1
-0b1.01 | 0b10.1 = -0b1.01
-0b1.01 ^ 0b10.1 = -0b11.11
~(floor(0b10.1)) = -3
type(-0b1.01) = <class 'binary.Binary'>
type(10.1) = <class 'binary.TwosComplement'>
Binary('0b10.1e-3').to_no_exponent() = 0b0.0101
Binary('0b10.1e-3').to_no_mantissa() = 0b101e-4
Binary('0b10.1e-3').to_sci_exponent() = 0b1.01e-2
Binary('0b10.1e-3').to_eng_exponent() = 0b101000000e-10
Binary('-0b1.01').to_twos_complement() = 10.11
Binary(TwosComplement('10.1')) = -1.1
Binary(TwosComplement('100001001000.1')) = -11110110111.1
Binary(TwosComplement(-1975.5)) = -11110110111.1
TwosComplement(-1975.5) = 100001001000.1
```
## Requirements:
- Python 3
- requires no `pip` packages (uses built-in `math` and `fractions` modules for
math operations, uses `unittest` for unit testing)
## Installation:
- see [https://pypi.org/project/binary-fractions/](https://pypi.org/project/binary-fractions/)
- `pip install binary-fractions`
## Testing, Maturity
- run `python3 binary_sample.py` to execute a simple sample program
- run `python3 binary_test.py` to execute all unit tests
- `Binary` is relatively mature, more than 1600 test cases have been written and all
passed.
## Contributions:
- PRs are welcome and very much appreciated! :+1:
- Please run and pass all existing 1600+ test cases in
[binary_test.py](https://github.com/Jonny-exe/binary-fractions/blob/master/binary_fractions/binary_test.py)
before issuing a PR.
- File Format: linted/beautified with [black](https://github.com/psf/black)
- This project uses static typing. [mypy](https://github.com/python/mypy)
is used for type checking.
- Test case format: [unittest](https://docs.python.org/3/library/unittest.html)
- Documentation format: [pydoc](https://docs.python.org/3/library/pydoc.html)
Enjoy :heart: !
"""
from __future__ import annotations # to allow type hinting in class methods
import math
import re
import unittest
from fractions import Fraction
from typing import Any, Union
_BINARY_WARNED_ABOUT_FLOAT = False # type: bool
_BINARY_RELATIVE_TOLERANCE = 1e-10 # type: float
# number of binary digits to the right of decimal point
_BINARY_PRECISION = 128 # type: int
_PREFIX = "0b" # type: str
_EXP = "e" # type: str
_NAN = "NaN" # type: str
_INF = "Inf" # type: str
_NINF = "-Inf" # type: str
# _BINARY_VERSION will be set automatically with git hook upon commit
_BINARY_VERSION = "20210721-160328" # type: str # format: date +%Y%m%d-%H%M%S
# _BINARY_TOTAL_TESTS will be set automatically with git hook upon commit
_BINARY_TOTAL_TESTS = 1646 # type: int # number of asserts in .py file
# see implementation of class Decimal:
# https://github.com/python/cpython/blob/3.9/Lib/_pydecimal.py
# https://docs.python.org/3/library/decimal.html
# see implementation of class Fraction:
# https://github.com/python/cpython/blob/3.9/Lib/fractions.py
# https://docs.python.org/3/library/fractions.html
# https://github.com/bradley101/fraction/blob/master/fraction/Fraction.py
##########################################################################
# CLASS TWOSCOMPLEMENT
##########################################################################
class TwosComplement(str):
"""Floating point class for representing twos-complement (2's complement).
If you are curious about Two's complement, read the following:
- https://en.wikipedia.org/wiki/Two%27s_complement
- https://janmr.com/blog/2010/07/bitwise-operators-and-negative-numbers/
The twos-complement format is as follows.
- there is no sign (-, +)
- there is no extra sign bit per se
- positive numbers must have a leading 0 to be recognized as positive
- hence positive numbers by definition always start with a 0
- negative numbers always start with a 1
- negative numbers can have an arbitrary number of additional leading 1s
- positive numbers can have an arbitrary number of additional leading 0s
- there must be one or more decimal bits
- there is an optional decimal point
- there are 0 or more fractional bits
- there is an optional exponent in decimal (e.g. e-34), the exponent is not binary
```
Syntax:
In 'regex' the syntax is
r"\s*((?=[01])(?P<int>[01]+)(\.(?P<frac>[01]*))?(E(?P<exp>[-+]?\d+))?)\s*\Z".
In simpler terms, the syntax is as follows:
[0,1]+[.][0,1]*[e[-,+][0-9]+]
integer bits (at least 1 bit required, leading bit indicates if pos. or neg.)
decimal point (optional, one or none)
fractional bits (optional, zero or more)
exponent (optional, possible with sign - or +, in decimal)
decimal | binary fraction | twos-complement
---------------------------------------------
-2.5e89 | -10.1e89 | 101.1e89
-6 | -110 | 1010
-5 | -101 | 1011
-0.5e3 | -0.1e3 | 1.1e3
-4 | -100 | 100
-3 | -11 | 101
-2.5 | -10.1 | 101.1
-0.25e3 | -0.01e3 | 1.11e3
-2 | -10 | 10
-1.5 | -1.1 | 10.1
-1 | -1 | 1
-0.5 | -0.1 | 1.1
-0.25 | -0.01 | 1.11
-0.125 | -0.001 | 1.111
0 | 0 | 0
1.5e-4 | 1.1e-4 | 01.1e-4
2.75e-4 | 10.11e-4 | 010.11e-4
0.25 | 0.01 | 0.01
0.5 | 0.1 | 0.1
1 | 1 | 01
1.5 | 1.1 | 01.1
2 | 10 | 010
2.75 | 10.11 | 010.11
3 | 11 | 011
4 | 100 | 0100
5 | 101 | 0101
6 | 110 | 0110
```
Valid TwosComplement strings are: 0, 1, 01, 10, 0.0, 1.1, 1., 0.1e+34,
11101.e-56, 0101.01e78. 000011.1000e0 is valid and is the same as 011.1.
Along the same line, 111101.0100000e-0 is valid and is the same as 101.01.
Invalid TwosComplement strings are: -1 (minus), +1 (plus),
.0 (no leading decimal digit),
12 (2 is not a binary digit),
1.2.3 (2 decimal points),
1e (missing exponent number),
1e-1.1 (decimal point in exponent).
"""
def __new__(
cls,
value: Union[int, float, Fraction, str] = 0,
length: int = -1,
rel_tol: float = _BINARY_RELATIVE_TOLERANCE,
ndigits: int = _BINARY_PRECISION,
simplify: bool = True,
warn_on_float: bool = False,
) -> TwosComplement:
"""Constructor.
Use __new__ and not __init__ because TwosComplement is immutable.
Allows string, float, integer, and Fraction as input for constructor.
If instance is contructed from a string, by default the string will
be simplified. With 'simplify' being False, attention is paid to
*not* modify the string or to modify it as little as possible.
With simplify being False, if given '1e1' it will remain as '1e1',
it will not change it to '1'. Same with '1000', which will not change
to '1e4'. In short, without simplification, attempts are made to keep
the string representation as close to the original as possible.
Examples:
* TwosComplement(4) returns '0100'
* TwosComplement(-2) returns '10'
* TwosComplement(-1.5) returns '10.1'
* TwosComplement(Fraction(-1.5)) returns '10.1'
* TwosComplement('110.101') returns '110.101'
* TwosComplement('110.101e-34') returns '110.101e-34'
Parameters:
value (int, float, Fraction, str): value of number
length (int): desired length of resulting string. If default -1, string
will be presented its normal (shortest) representation. If
larger, string will be prefixed with leading bits to achieve
desired length. If length is too short to fit number, an
exception will be raised.
Example of length 4 is '01.1'.
ndigits (int): desired digits after decimal point. 'ndigits' is only
relevant for Fractions.
rel_tol (float): relative tolerance that influences precision further.
A bigger tolerance leads to a possibly less precise result.
A smaller tolerance leads to a possibly more precise result.
'rel_tol' is only relevant for floats.
simplify (bool): If True, try to simplify string representation.
If False, try to leave the string representation as much as is.
'simplify' is only relevant for strings.
warn_on_float (bool): If True print a warning statement to stdout to
warn about possible loss in precision in case of conversion from
float to TwosComplement.
If False, print no warning to stdout.
'warn_on_float' is only relevant for floats.
Returns:
TwosComplement: created immutable instance representing twos-complement
number as a string of class TwosComplement.
Testcases:
model: self.assertIsInstance(TwosComplement(X1), TwosComplement)
cases: some test cases for return class
- 1
- -2
- -2.5
- '10'
- '010'
- Fraction(3,4)
model: self.assertEqual(TwosComplement(X1), X2)
cases: some test cases for equal
- -2 ==> '10'
- 2 ==> '010'
- -1.5 ==> '10.1'
- 3.5 ==> '011.5'
- '10.101' ==> '10.101'
- '0001.00' ==> '01'
- Fraction(-3,2) ==> '10.1'
- Fraction(7,2) ==> '011.5'
model: with self.assertRaises(ValueError):
TwosComplement(X1)
cases: some test cases for raising ValueError
- "102"
- "nan"
"""
if isinstance(value, int):
return str.__new__(cls, TwosComplement._int2twoscomp(value, length))
if isinstance(value, float):
return str.__new__(
cls,
TwosComplement._float2twoscomp(value, length, rel_tol, warn_on_float),
)
if isinstance(value, Fraction):
return str.__new__(cls, TwosComplement._fraction2twoscomp(value, length, ndigits))
if isinstance(value, str):
return str.__new__(
cls, TwosComplement._str2twoscomp(value, length, simplify=simplify)
)
# any other types
raise TypeError(
f"Cannot convert {value} of type {type(value)} to TwosComplement"
)
@staticmethod
def _int2twoscomp(value: int, length: int = -1) -> str:
"""Computes the two's complement of int value.
This is a utility function.
Users should use the constructor TwosComplement(value) instead.
Parameters:
value (int): integer to convert into twos-complement string.
length (int): desired length of string. If default -1, string
will be presented its normal (shortest) representation. If
larger, string will be prefixed with leading bits to achieve
desired length. If length is too short to fit number, an
exception will be raised.
Example of length 4 is '01.1'.
Returns:
str: string containing twos-complement of value
"""
if value == 0:
digits = 1 # type: int
elif value > 0:
# add 1 for leading '0' in positive numbers
# less precise: digits = math.ceil(math.log(abs(value + 1), 2)) + 1
digits = len(bin(value).replace(_PREFIX, "")) + 1
else: # negative
# less precise: digits = math.ceil(math.log(abs(value), 2)) + 1
digits = len(bin(value + 1).replace(_PREFIX, ""))
# digits = number of bits required to represent this
# negative number in twos-complement
if length == -1:
length = digits
if length < digits:
raise OverflowError(f"Argument {value} does not fit into {length} digits.")
if value == 0:
result = "0" * length
elif value < 0: # negative
value = value - (1 << length) # compute negative value
result = bin(value & ((2 ** length) - 1)).replace(_PREFIX, "")
result = "1" * (len(result) - length) + result
else: # positive
result = "0" + bin(value).replace(_PREFIX, "")
result = "0" * (length - len(result)) + result
if length != -1:
le = len(result)
if le > length:
raise OverflowError
result = result[0] * (length - le) + result
return result
@staticmethod
def _frac2twoscomp(
value: float, length: int = -1, rel_tol: float = _BINARY_RELATIVE_TOLERANCE
) -> str:
"""Computes the two's complement of the fractional part (mantissa) of a float.
This is a utility function.
Users should use the constructor TwosComplement(f-int(f)) instead.
The returned string always has one integer digit, followed by a decimal point.
The integer digit indicates the sign.
The decimal part consists of at least 1 bit.
Hence, the shortest values are 0.0, 0.1, 1.0, and 1.1.
This function has rounding errors as it deals with floats.
_frac2twoscomp(+1.0000000000000000000000000000000001) returns '0.0'.
_frac2twoscomp(-0.9999999999999999999999999999999999) returns '1.0'
because it is rounded to -1.
Use the method _fraction2twoscomp() using Fractions to avoid rounding
errors.
Examples:
* For -3.5 it computes the twos-complement of -0.5.
So, _frac2twoscomp(-3.5) returns '1.1'.
* _frac2twoscomp(+3.5) returns '0.1'.
* _frac2twoscomp(-3.375) returns '1.101'.
* _frac2twoscomp(+3.375) returns '1.11'.
Parameters:
value (float): number whose mantissa will be converted to twos-complement.
length (int): desired length of resulting string. If -1, result is neither
prefixed nor truncated. A shorter length will truncate the mantissa,
losing precision. A larger length will prefix the decimal digits
with additional sign bits to produce a resulting string of specified
lenght.
Example of length 4 is '01.1'.
rel_tol (float): relative tolerance that influences precision further.
A bigger tolerance leads to a possibly less precise result.
A smaller tolerance leads to a possibly more precise result.
Returns:
str: twos-complement string of the mantissa
"""
if length < 1 and length != -1:
raise ValueError(f"Argument {length} has be greater than 0, or default -1.")
fp, ip = math.modf(value)
afp = abs(fp)
result = ""
i = 1
if value == 0:
result = "0.0"
elif fp == 0:
result = "0.0" if ip >= 0 else "1.0"
elif fp >= 0: # Positive
rest = 0.0
while not (math.isclose(rest, fp, rel_tol=rel_tol)):
b = 2 ** -i
if b + rest <= fp:
result += "1"
rest += b
else:
result += "0"
i += 1
result = "0." + result
else: # Negative
rest = 1.0
while not (math.isclose(rest, afp, rel_tol=rel_tol)):
b = 2 ** -i
if rest - b < afp:
result += "0"
else:
rest -= b
result += "1"
i += 1
result = "0" if result == "" else result
result = "1." + result
if length == -1:
result = result
elif length > len(result): # fill
sign = result[0]
result = sign * (length - len(result)) + result
elif length < len(result): # truncate
result = result[0:length]
return result
@staticmethod
def _float2twoscomp(
value: float,
length: int = -1,
rel_tol: float = _BINARY_RELATIVE_TOLERANCE,
warn_on_float: bool = False,
) -> str:
"""Converts float to two's-complement.
This is a utility function.
Users should use the constructor TwosComplement(value) instead.
If maximum precision is desired, use Fractions instead of floats.
Parameters:
value (float): number to be converted to twos-complement.
length (int): desired length of resulting string. If -1, result is neither
prefixed nor truncated. If length is too short to fit value, an
exception is raised. A larger length will prefix the decimal digits
with additional sign bits to produce a resulting string of specified
lenght.
Example of length 4 is '01.1'.
rel_tol (float): relative tolerance that influences precision further.
A bigger tolerance leads to a possibly less precise result.
A smaller tolerance leads to a possibly more precise result.
Returns:
str: twos-complement string of value
"""
if math.isnan(value) or math.isinf(value):
raise ArithmeticError(
f"ArithmeticError: argument {value} is NaN or infinity."
)
global _BINARY_WARNED_ABOUT_FLOAT
if value != int(value): # not an integer
if not _BINARY_WARNED_ABOUT_FLOAT:
_BINARY_WARNED_ABOUT_FLOAT = True
if warn_on_float:
print(
"Warning: possible loss of precision "
"due to mixing floats and TwosComplement. "
"Consider using Fraction instead of float."
)
# more precise to use Fraction than float
return TwosComplement._fraction2twoscomp(Fraction(value), length)
@staticmethod
def _float2twoscomp_implementation_with_less_precision(
value: float, length: int = -1, rel_tol: float = _BINARY_RELATIVE_TOLERANCE
) -> str:
"""Converts float to two's-complement.
This is a utility function.
Users should use the constructor TwosComplement(value) instead.
Does the same as _float2twoscomp() but with possibly less precision.
"""
if math.isnan(value) or math.isinf(value):
raise ArithmeticError(
f"ArithmeticError: argument {value} is NaN or infinity."
)
fp, ip = math.modf(value)
if fp == 0:
return TwosComplement._int2twoscomp(int(ip), length)
if fp < 0: # negative
intresult = TwosComplement._int2twoscomp(math.floor(value), -1)
else:
intresult = TwosComplement._int2twoscomp(int(ip), -1)
if intresult == "0" and fp < 0: # -0.x
intresult = "1"
fracresult = TwosComplement._frac2twoscomp(fp, -1)
result = intresult + "." + fracresult[2:]
if length < len(result) and length != -1:
raise OverflowError(f"Argument {value} does not fit into {length} digits.")
if length != -1:
sign = result[0]
result = sign * (length - len(result)) + result
return result
@staticmethod
def _fraction2twoscomp(
value: Fraction, length: int = -1, ndigits: int = _BINARY_PRECISION
) -> str:
"""Converts fraction to two's-complement.
This is a utility function.
Users should use the constructor TwosComplement(value) instead.
First parameter 'ndigits', then secundarily parameter 'length' will
be applied to result. 'ndigits' influences digits after decimal point,
'length' influences digits (sign bits) before the decimal point.
Parameters:
value (Fraction): number to be converted to twos-complement.
length (int): desired length of resulting string. If -1, result is neither
prefixed nor truncated. If length is too short to fit value, an
exception is raised. A larger length will prefix the decimal digits
with additional sign bits to produce a resulting string of specified
lenght.
Example of length 4 is '01.1'.
ndigits (int): desired digits after decimal point.
Returns:
str: twos-complement string of value
"""
if value.denominator == 1:
result = TwosComplement._int2twoscomp(value.numerator, length=length)
return result
# uses Fractions for computation for more precision
if value.numerator >= 0: # positive
# alternative implementation: just call function in Binary:
# result = Binary.fraction_to_string(value, ndigits, simplify=True)
# But to keep TwosComplement independent of Binary it was redone
# here.
result = bin(int(value)).replace(_PREFIX, "")
fraction_number = value - int(value)
if fraction_number > 0:
result += "."
rest = Fraction(0)
ii = 1
while ii < ndigits + 1:
b = Fraction(1, 2 ** ii)
if rest + b < fraction_number:
result += "1"
rest += b
elif rest + b > fraction_number:
result += "0"
elif rest + b == fraction_number:
result += "1"
break
ii += 1
if result[0] != "0":
result = "0" + result
else: # negative
absvalue = -value
digits = len(bin(int(absvalue)).replace(_PREFIX, "")) + 1
resultintpart = 2 ** digits - math.ceil(absvalue)
result = bin(resultintpart).replace(_PREFIX, "")
# remove duplicate 1s on left
result = "1" + result.lstrip("1")
fraction_number = absvalue - int(absvalue)
if fraction_number > 0:
result += "."
rest = Fraction(1)
ii = 1
while ii < ndigits + 1:
b = Fraction(1, 2 ** ii)
if rest - b < fraction_number:
result += "0"
elif rest - b > fraction_number:
rest -= b
result += "1"
elif rest - b == fraction_number:
result += "1"
break
ii += 1
# remove 0s on right
if "." in result:
result = result.rstrip("0")
if length != -1:
le = len(result)
if le > length:
raise OverflowError
result = result[0] * (length - le) + result
return result
@staticmethod
def _str2twoscomp(value: str, length: int = -1, simplify: bool = True) -> str:
"""Converts two's-complement string to possibly refined two's-complement
string.
This is a utility function.
Users should use the constructor TwosComplement(value) instead.
A possible simplification will be done before a possible length
extension.
Parameters:
value (str): twos-complement string to be converted to twos-complement.
length (int): desired length of resulting string. If -1, result is
not prefixed. If length is too short to fit value, an
exception is raised. A larger length will prefix the decimal digits
with additional sign bits to produce a resulting string of specified
length.
Example of length 4 is '01.1'.
simplify (bool): If True, result will be simplified. If False, result
will be left unchanged as much as possible.
Returns:
str: twos-complement string of value
"""
if TwosComplement.istwoscomplement(value):
if length < len(value) and length != -1:
raise OverflowError(
f"Argument {value} does not fit into {length} digits."
)
if simplify:
value = TwosComplement.simplify(value)
if length != -1:
sign = value[0]
value = sign * (length - len(value)) + value
return value
else:
raise ValueError(f"Argument {value} not a valid twos-complement.")
def istwoscomplement(value: str) -> bool:
"""Determine if string content has a valid two's-complement syntax.
Parameters:
value (str): string to check
Returns:
bool: True if value is a valid twos-complement. False otherwise.
"""
try:
TwosComplement.components(value)
# don't catch TypeError
except ValueError:
return False
return True
def components(
self_value: Union[str, TwosComplement], simplify: bool = True
) -> tuple[int, str, str, int]:
"""Returns sign, integer part (indicates sign in first bit), fractional
part, and exponent as a tuple of int, str, str, and int.
This is both a function and a method.
Examples:
Here are some examples for `simplify` being False.
* For 3.25*4, input '11.01e2' returns (1, '11', '01', 2).
* For 0, input '0' returns (0, '0', '', 0).
* For -1, input '1' returns (1, '1', '', 0).
* For 1, input '01' returns (0, '01', '', 0).
* For -0.5, input 1.1 returns (1, '1', '1', 0).
* For neg. number, input 101.010e-4 returns (1, '101', '010', -4).
* For pos. number, input 0101.010e-4 returns (0, '0101', '010', -4).
* For input 111101.010000e-4 returns (1, '111101', '010000', -4).
Here are some examples for `simplify` being True.
* For -3.25*4, input '1111101.11e2' returns (1, '101', '11', 2).
* For input '11111111.0111e4' returns (1, '1', '0111', 4).
* For 0, input '0' returns (0, '0', '', 0).
* For -1, input '1' returns (1, '1', '', 0).
* For 1, input '01' returns (0, '01', '', 0).
* For -0.5, input 1.1 returns (1, '1', '1', 0).
* For neg. number, input 111101.0100e-4 returns (1, '101', '01', -4).
* For pos. number, input 0000101.0100e-4 returns (0, '0101', '01', -4).
Parameters:
self_value (str, TwosComplement): twos-complement from which to
derive the components.
simplify (bool): If True simplify output by performing cleanup and
removing unnecessary digits.
If False, then produce exact as-is twos-complement components
without any cleanup or simplifications.
Returns:
tuple: tuple of sign (int), integer part (str) including a sign bit,
fractional part (str), exponent (int). Sign is int 1 for negative (-).
Sign is int 0 for positive (+).
"""
if not isinstance(self_value, str) and not isinstance(
self_value, TwosComplement
):
raise TypeError(
f"Argument {self_value} must be of type str or TwosComplement."
)
# crud for parsing strings
#
# Regular expression used for parsing twos-complement strings. Additional
# comments:
#
# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
# whitespace. But note that the specification disallows whitespace in
# a numeric string.
#
# 2. For finite numbers the body of the
# number before the optional exponent must have
# at least one binary digit. The
# lookahead expression '(?=[01])' checks this.
_parser = re.compile(
r""" # A twoscomplement string consists of:
\s*
(
(?=[01]) # lookahead: a number (with at least one digit)
(?P<int>[01]+) # non-empty integer part with at least 1 digit
(\.(?P<frac>[01]*))? # followed by an optional fractional part
(E(?P<exp>[-+]?\d+))? # followed by an optional exponent
)
\s*
\Z
""",
re.VERBOSE | re.IGNORECASE,
).match
m = _parser(self_value)
if m is None:
raise ValueError(
f"Invalid literal: {self_value}. "
+ "Not a valid twos-complement string."
)
intpart = m.group("int")
fracpart = m.group("frac") or ""
exp = int(m.group("exp") or "0")
# according to parser int cannot be empty
if intpart[0] == "0":
sign = 0 # "+"
else:
sign = 1 # "-"
if simplify:
fracpart = fracpart.rstrip("0")
if sign: # neg
intpart = "1" + intpart.lstrip("1")
else: # pos
intpart = "0" + intpart.lstrip("0")
return (sign, intpart, fracpart, exp)
def simplify(self_value: Union[str, TwosComplement]) -> Union[str, TwosComplement]:
"""Simplifies two's-complement strings.
This is a utility function as well as a method.
Removes leading duplicate 0s or 1s to the left of decimal point.
Removes trailing duplicate 0s after decimal point.
Removes unnecessary exponent 0.
Parameters:
self_value (str, TwosComplement): twos-complement string to be simplified
Returns:
Union[str, TwosComplement]: returns simplied twos-complement. Return type is
str if input was of class str, return type is
TwosComplement if input was of class TwosComplement.
"""
if not isinstance(self_value, str) and not isinstance(
self_value, TwosComplement
):
raise TypeError(
f"Argument {self_value} must be of type str or TwosComplement."
)
value = str(self_value)
sign, intpart, fracpart, exp = TwosComplement.components(value)
if len(intpart) and intpart[0] == "1":
# remove duplicate 1s on left
intpart = "1" + intpart.lstrip("1")
elif len(intpart) and intpart[0] == "0":
# remove duplicate 0s on left
intpart = "0" + intpart.lstrip("0")
# remove duplicate 0s to right of decimal point
fracpart = fracpart.rstrip("0")
if fracpart != "":
fracpart = "." + fracpart
exppart = "" if exp == 0 else _EXP + str(exp)
result = intpart + fracpart + exppart
if isinstance(self_value, TwosComplement):
result = TwosComplement(result)
return result
def to_fraction(self_value: Union[str, TwosComplement]) -> Fraction:
"""Converts two's-complement to Fraction.
This is a utility function as well as a method.
Do *NOT* use it on binary fractions strings!
Parameters:
self_value (str, TwosComplement): twos-complement string to be
converted to Fraction
Returns:
Fraction: returned value as a Fraction
"""
if not isinstance(self_value, str) and not isinstance(