-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinstr.py
1604 lines (1296 loc) · 72.3 KB
/
binstr.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/env python
###########################################################################
# Copyright (C) 2011 David McEwan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
###########################################################################
# This file contains some utility functions for creating and operating
# on strings of binary digits.
# It is not intended to be the fastest or most efficient.
# It has been designed to be completely predictable, i.e. Strange inputs
# will cause an AssertionError to be raised.
#
# However, it is useful for ensuring the correctness of each bit in an
# easy-to-use and easily printable manner.
# This fits in well when generating code in other languages like Verilog,
# C and Assembler.
# Obviously the other main use would be if you already have strings of
# binary that you need to fiddle with.
#
#----------------------
# Implementation Notes:
#----------------------
# The term b_string is used to refer to a string containing only 0s and 1s.
# In functions the letters A and B always refers to an input b_string.
# The variable t used in most functions stands for temporary.
# In the gray conversion functions the variables b and g are used instead of
# t for clarity.
#
# The function naming scheme is as follows:
# - 'b_' prefix means that a valid b_string must be given as input.
# - '_b' suffix means that a valid b_string will be returned as the output
# where the input was not a valid b_string.
# - The rest of the name describes the operation of the function.
#
# To test that everything is working e.g. before a commit run the unit tests
# with some commands like:
# cd binstr
# python binstr_test.py
# python3 binstr_test.py
#
# When binstr.py is executed as __main__ it will simply print the docstrings of
# all the functions using documentation().
# The docstring for documentation() will not be printed.
# Bitwise Operations {{{
def b_and(A='00000000', B='00000000', align='right'): #{{{
'''
Perform a bitwise AND on two strings of binary digits, A and B.
The align argument can be used to align the shortest of A and B to one
side of the other.
The returned string is the same length as the longest input.
E.g. b_and('0101', '0011') returns '0001'
b_and('01010000', '0011') returns '00000000'
b_and('01010000', '0011', align='left') returns '00010000'
'''
assert b_validate(A) == True, \
'Invalid b_string : A : %(actual)s' % {'actual': str(A)}
assert b_validate(B) == True, \
'Invalid b_string : B : %(actual)s' % {'actual': str(B)}
assert type(align) is str, \
'Invalid type : align : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(align)),
}
assert align == 'right' or align == 'left', \
'Invalid value: align : Expected %(expect)s : %(actual)s' % {
'expect': '"left" OR "right"',
'actual': str(align),
}
if len(A) >= len(B): (p, q) = (A, B)
else: (p, q) = (B, A)
del A, B
if align == 'right': q = '0'*(len(p) - len(q)) + q
else: q = q + '0'*(len(p) - len(q))
return ''.join([str(int( bool(int(a)) and bool(int(b)) )) for (a, b) in zip(p, q)])
# }}} End of b_and()
def b_nand(A='00000000', B='00000000', align='right'): #{{{
'''
Perform a bitwise NAND on two strings of binary digits, A and B.
The align argument can be used to align the shortest of A and B to one
side of the other.
The returned string is the same length as the longest input.
E.g. b_nand('0101', '0011') returns '1110'
b_nand('01010000', '0011') returns '11111111'
b_nand('01010000', '0011', align='left') returns '11101111'
'''
assert b_validate(A) == True, \
'Invalid b_string : A : %(actual)s' % {'actual': str(A)}
assert b_validate(B) == True, \
'Invalid b_string : B : %(actual)s' % {'actual': str(B)}
assert type(align) is str, \
'Invalid type : align : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(align)),
}
assert align == 'right' or align == 'left', \
'Invalid value: align : Expected %(expect)s : %(actual)s' % {
'expect': '"left" OR "right"',
'actual': str(align),
}
if len(A) >= len(B): (p, q) = (A, B)
else: (p, q) = (B, A)
del A, B
if align == 'right': q = '0'*(len(p) - len(q)) + q
else: q = q + '0'*(len(p) - len(q))
return ''.join([str(int( not( bool(int(a)) and bool(int(b)) ) )) for (a, b) in zip(p, q)])
# }}} End of b_nand()
def b_or(A='00000000', B='00000000', align='right'): # {{{
'''
Perform a bitwise OR on two strings of binary digits, A and B.
The align argument can be used to align the shortest of A and B to one
side of the other.
The returned string is the same length as the longest input.
E.g. b_or('0101', '0011') returns '0111'
b_or('01010000', '0011') returns '01010011'
b_or('01010000', '0011', align='left') returns '01110000'
'''
assert b_validate(A) == True, \
'Invalid b_string : A : %(actual)s' % {'actual': str(A)}
assert b_validate(B) == True, \
'Invalid b_string : B : %(actual)s' % {'actual': str(B)}
assert type(align) is str, \
'Invalid type : align : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(align)),
}
assert align == 'right' or align == 'left', \
'Invalid value: align : Expected %(expect)s : %(actual)s' % {
'expect': '"left" OR "right"',
'actual': str(align),
}
if len(A) >= len(B): (p, q) = (A, B)
else: (p, q) = (B, A)
del A, B
if align == 'right': q = '0'*(len(p) - len(q)) + q
else: q = q + '0'*(len(p) - len(q))
return ''.join([str(int( bool(int(a)) or bool(int(b)) )) for (a, b) in zip(p, q)])
# }}} End of b_or()
def b_nor(A='00000000', B='00000000', align='right'): # {{{
'''
Perform a bitwise NOR on two strings of binary digits, A and B.
The align argument can be used to align the shortest of A and B to one
side of the other.
The returned string is the same length as the longest input.
E.g. b_or('0101', '0011') returns '1000'
b_or('01010000', '0011') returns '10101100'
b_or('01010000', '0011', align='left') returns '10001111'
'''
assert b_validate(A) == True, \
'Invalid b_string : A : %(actual)s' % {'actual': str(A)}
assert b_validate(B) == True, \
'Invalid b_string : B : %(actual)s' % {'actual': str(B)}
assert type(align) is str, \
'Invalid type : align : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(align)),
}
assert align == 'right' or align == 'left', \
'Invalid value: align : Expected %(expect)s : %(actual)s' % {
'expect': '"left" OR "right"',
'actual': str(align),
}
if len(A) >= len(B): (p, q) = (A, B)
else: (p, q) = (B, A)
del A, B
if align == 'right': q = '0'*(len(p) - len(q)) + q
else: q = q + '0'*(len(p) - len(q))
return ''.join([str(int( not( bool(int(a)) or bool(int(b)) ) )) for (a, b) in zip(p, q)])
# }}} End of b_nor()
def b_xor(A='00000000', B='00000000', align='right'): # {{{
'''
Perform a bitwise XOR on two strings of binary digits, A and B.
The align argument can be used to align the shortest of A and B to one
side of the other.
The returned string is the same length as the longest input.
E.g. b_or('0101', '0011') returns '0110'
b_or('01010000', '0011') returns '01010011'
b_or('01010000', '0011', align='left') returns '01100000'
'''
assert b_validate(A) == True, \
'Invalid b_string : A : %(actual)s' % {'actual': str(A)}
assert b_validate(B) == True, \
'Invalid b_string : B : %(actual)s' % {'actual': str(B)}
assert type(align) is str, \
'Invalid type : align : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(align)),
}
assert align == 'right' or align == 'left', \
'Invalid value: align : Expected %(expect)s : %(actual)s' % {
'expect': '"left" OR "right"',
'actual': str(align),
}
if len(A) >= len(B): (p, q) = (A, B)
else: (p, q) = (B, A)
del A, B
if align == 'right': q = '0'*(len(p) - len(q)) + q
else: q = q + '0'*(len(p) - len(q))
return ''.join([str(int( bool(int(a)) ^ bool(int(b)) )) for (a, b) in zip(p, q)])
# }}} End of b_xor()
def b_nxor(A='00000000', B='00000000', align='right'): # {{{
'''
Perform a bitwise NXOR on two strings of binary digits, A and B.
The align argument can be used to align the shortest of A and B to one
side of the other.
The returned string is the same length as the longest input.
E.g. b_or('0101', '0011') returns '1001'
b_or('01010000', '0011') returns '10101100'
b_or('01010000', '0011', align='left') returns '10011111'
'''
assert b_validate(A) == True, \
'Invalid b_string : A : %(actual)s' % {'actual': str(A)}
assert b_validate(B) == True, \
'Invalid b_string : B : %(actual)s' % {'actual': str(B)}
assert type(align) is str, \
'Invalid type : align : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(align)),
}
assert align == 'right' or align == 'left', \
'Invalid value: align : Expected %(expect)s : %(actual)s' % {
'expect': '"left" OR "right"',
'actual': str(align),
}
if len(A) >= len(B): (p, q) = (A, B)
else: (p, q) = (B, A)
del A, B
if align == 'right': q = '0'*(len(p) - len(q)) + q
else: q = q + '0'*(len(p) - len(q))
return ''.join([str(int( not( bool(int(a)) ^ bool(int(b)) ) )) for (a, b) in zip(p, q)])
# }}} End of b_nxor()
def b_not(A='00000000'): # {{{
'''
Perform a bitwise NOT (inversion) on an input string.
The returned string is the same length as the input.
E.g. b_or() returns '11111111'
b_or('0101') returns '1010'
'''
assert b_validate(A) == True, \
'Invalid b_string : A : %(actual)s' % {'actual': str(A)}
return ''.join([str(int( not( bool(int(a)) ) )) for a in A])
# }}} End of b_not()
# }}} End of Bitwise Operations
# Logical Operations {{{
def b_land(A='0'): #{{{
'''
Perform a logical AND on a string of binary digits.
The returned string is always one digit in length.
E.g. b_and('11111111') returns '1'
b_and('01010000') returns '0'
b_and('00000000') returns '0'
'''
assert b_validate(A) == True, \
'Invalid b_string : A : %(actual)s' % {'actual': str(A)}
if len(A) >= 1 and A.find('0') < 0: return '1'
else: return '0'
# }}} End of b_land()
def b_lnand(A='0'): #{{{
'''
Perform a logical NAND on a string of binary digits.
The returned string is always one digit in length.
E.g. b_and('11111111') returns '0'
b_and('01010000') returns '1'
b_and('00000000') returns '1'
'''
assert b_validate(A) == True, \
'Invalid b_string : A : %(actual)s' % {'actual': str(A)}
if len(A) >= 1 and A.find('0') < 0: return '0'
else: return '1'
# }}} End of b_lnand()
def b_lor(A='0'): #{{{
'''
Perform a logical OR on a string of binary digits.
The returned string is always one digit in length.
E.g. b_and('11111111') returns '1'
b_and('01010000') returns '1'
b_and('00000000') returns '0'
'''
assert b_validate(A) == True, \
'Invalid b_string : A : %(actual)s' % {'actual': str(A)}
if len(A) >= 1 and A.find('1') < 0: return '0'
else: return '1'
# }}} End of b_lor()
def b_lnor(A='0'): #{{{
'''
Perform a logical NOR on a string of binary digits.
The returned string is always one digit in length.
E.g. b_and('11111111') returns '0'
b_and('01010000') returns '0'
b_and('00000000') returns '1'
'''
assert b_validate(A) == True, \
'Invalid b_string : A : %(actual)s' % {'actual': str(A)}
if len(A) >= 1 and A.find('1') < 0: return '1'
else: return '0'
# }}} End of b_lnor()
def b_lxor(A='0'): #{{{
'''
Perform a logical XOR on a string of binary digits.
The returned string is always one digit in length.
E.g. b_and('11111111') returns '0'
b_and('01010000') returns '0'
b_and('01110000') returns '1'
b_and('00000001') returns '1'
b_and('00000000') returns '0'
'''
assert b_validate(A) == True, \
'Invalid b_string : A : %(actual)s' % {'actual': str(A)}
if len(A) >= 1 and A.count('1') % 2 == 0: return '0'
else: return '1'
# }}} End of b_lxor()
def b_lnxor(A='0'): #{{{
'''
Perform a logical NXOR on a string of binary digits.
The returned string is always one digit in length.
E.g. b_and('11111111') returns '1'
b_and('01010000') returns '1'
b_and('01110000') returns '0'
b_and('00000001') returns '0'
b_and('00000000') returns '1'
'''
assert b_validate(A) == True, \
'Invalid b_string : A : %(actual)s' % {'actual': str(A)}
if len(A) >= 1 and A.count('1') % 2 == 0: return '1'
else: return '0'
# }}} End of b_lnxor()
# }}} End of Logical Operations
# Convertions To Binary Strings {{{
def int_to_b(num=0, width=8, endian='big', chop='most'): # {{{
'''
Convert a positive integer to a binary string.
The width can be set to an arbitrary value but defaults to 8.
If the width is less than the number of bits required to represent num
then only the least significant bits are returned.
However, by setting chop to 'least' only the most significant bits are
returned.
Clearly, chop is only relevant when the width is specified to be less
then the width of num.
The endianess is big by default but can be set to little to return a
bit reversal.
The returned string is can be converted to an int in Python by setting
the base to 2 e.g.:'int( int_to_b(...) , 2 )'.
E.g. int_to_b() returns '00000000'
int_to_b(5) returns '00000101'
int_to_b(0xF5, width=10, endian='little') returns '1010111100'
int_to_b(0xF5, width=7) returns '1110101'
int_to_b(0xF5, width=7, chop='least') returns '1111010'
'''
assert type(num) is int or type(num) is long, \
'Invalid type : num : Expected %(expect)s : %(actual)s' % {
'expect': str(type(int())) + ' OR ' + str(type(long())),
'actual': str(type(num)),
}
assert num >= 0, \
'Invalid value : num : Expected %(expect)s : %(actual)s' % {
'expect': 'num >= 0',
'actual': str(num),
}
assert type(width) is int, \
'Invalid type : width : Expected %(expect)s : %(actual)s' % {
'expect': str(type(int())),
'actual': str(type(width)),
}
assert width >= 0, \
'Invalid value : width : Expected %(expect)s : %(actual)s' % {
'expect': 'width >= 0',
'actual': str(width),
}
assert type(endian) is str, \
'Invalid type : endian : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(endian)),
}
assert endian == 'little' or endian == 'big', \
'Invalid value: endian : Expected %(expect)s : %(actual)s' % {
'expect': '"little" OR "big"',
'actual': str(endian),
}
assert type(chop) is str, \
'Invalid type : chop : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(chop)),
}
assert chop == 'most' or chop == 'least', \
'Invalid value: chop : Expected %(expect)s : %(actual)s' % {
'expect': '"most" OR "least"',
'actual': str(chop),
}
# The actual conversion. Not dependent on the behaviour of bin().
a = num
b = ''
while a:
b += str(a % 2)
a = int(a / 2)
t = b[::-1]
del a, b
if len(t) > width:
if chop == 'most': t = t[(-1 * width):] # Remove most significant bits
elif chop == 'least': t = t[:width] # Remove least significant bits
else: t = '0'*(width - len(t)) + t # Add padding zeros
if endian == 'little': t = t[::-1] # Reverse the string
return t
# }}} End of int_to_b()
def frac_to_b(num=0.0, width=8, endian='big'): # {{{
'''
Convert a positive float which is less than 1.0 to a binary string.
The returned value is 0xFF*num represented as a binary string
when the width is 8 (default).
This is useful for simulating fixed point arithmetic.
The endianess is little by default but can be set to big to return a
bit reversal.
The returned string is can be converted to an int in Python by setting
the base to 2 e.g.:'int( frac_to_b(...) , 2 )'.
E.g. frac_to_b() returns 00000000
frac_to_b(0.3, 5) returns 01010
frac_to_b(0.5, width=10, endian='little') returns 0000000001
'''
assert type(num) is float, \
'Invalid type : num : Expected %(expect)s : %(actual)s' % {
'expect': str(type(float())),
'actual': str(type(num)),
}
assert num < 1.0, \
'Invalid value : num : Expected %(expect)s : %(actual)s' % {
'expect': 'num < 1.0',
'actual': str(num),
}
assert type(width) is int, \
'Invalid type : width : Expected %(expect)s : %(actual)s' % {
'expect': str(type(int())),
'actual': str(type(width)),
}
assert width >= 0, \
'Invalid value : width : Expected %(expect)s : %(actual)s' % {
'expect': 'width >= 0',
'actual': str(width),
}
assert type(endian) is str, \
'Invalid type : endian : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(endian)),
}
assert endian == 'little' or endian == 'big', \
'Invalid value: endian : Expected %(expect)s : %(actual)s' % {
'expect': '"little" OR "big"',
'actual': str(endian),
}
a = int(round(num * 2**width)) # Move the most significant bit to the correct place and round.
b = ''
while a:
b += str(a % 2)
a = int(a / 2)
t = b[::-1]
del a, b
if len(t) > width: t = t[:width] # Remove least significant bits
else: t = '0'*(width - len(t)) + t # Add padding zeros
if endian == 'little': t = t[::-1] # Reverse the string
return t
# }}} End of frac_to_b()
def str_to_b(instr='', char_width=8, endian='big', prefix='', suffix='', parity='N'): # {{{
'''
Convert an ASCII string into a string of binary digits.
The bit-endianness of each character can be set with the char_width and
endian arguments although these are set to 8 bits wide and big
endian by default.
A prefix and suffix can also be specified to be added to each character.
This can be useful for simulating start and stop bits.
The parity argument can be used to add a parity bit.
The allowed options are;
N = None. No parity bit will be inserted.
pO = prefixed Odd. Odd parity bit will be prefixed to sequence.
sO = suffixed Odd. Odd parity bit will be suffixed to character.
pE = prefixed Even. Even parity bit will be prefixed to character.
sE = suffixed Even. Even parity bit will be suffixed to character.
Mark and Space parity bits can be included with the prefix and suffix
arguments as they are always fixed to either 1 or 0.
E.g. str_to_b() returns ''
str_to_b('\\x00') returns '00000000'
str_to_b('abc') returns '011000010110001001100011'
str_to_b('U') returns '01010101'
str_to_b('U', endian='little') returns '10101010'
str_to_b('U', char_width=7) returns '1010101'
str_to_b('U', prefix='1111', suffix='0000') returns '1111010101010000'
str_to_b('\\x00', parity='pO') returns '100000000'
str_to_b('U', parity='sE') returns '010101010'
'''
assert type(instr) is str, \
'Invalid type : instr : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(instr)),
}
for (i, c) in enumerate(instr):
assert ord(c) < 256, \
'Invalid value : Character "%(c)s" (%(o)s) at position %(i)s is not valid ASCII (< 256)' % {
'c': str(c),
'o': ord(c),
'i': str(i),
}
assert type(char_width) is int, \
'Invalid type : char_width : Expected %(expect)s : %(actual)s' % {
'expect': str(type(int())),
'actual': str(type(char_width)),
}
assert char_width >= 0, \
'Invalid value : char_width : Expected %(expect)s : %(actual)s' % {
'expect': 'char_width >= 0',
'actual': str(char_width),
}
assert type(endian) is str, \
'Invalid type : endian : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(endian)),
}
assert endian == 'little' or endian == 'big', \
'Invalid value: endian : Expected %(expect)s : %(actual)s' % {
'expect': '"little" OR "big"',
'actual': str(endian),
}
assert type(parity) is str, \
'Invalid type : parity : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(parity)),
}
assert parity == 'N' or \
parity == 'pO' or \
parity == 'sO' or \
parity == 'pE' or \
parity == 'sE', \
'Invalid value: prefix : Expected %(expect)s : %(actual)s.' % {
'expect': '"N" OR "pO" OR "sO" OR "pE" OR "sE"',
'actual': str(prefix),
}
assert b_validate(prefix, fail_empty=False) == True, \
'Invalid b_string : prefix : %(actual)s' % {'actual': str(prefix)}
assert b_validate(suffix, fail_empty=False) == True, \
'Invalid b_string : suffix : %(actual)s' % {'actual': str(suffix)}
t = ''
for c in (instr):
b_c = int_to_b(ord(c), width=char_width, endian=endian, chop='most')
t += prefix
if parity == 'pO': t += b_lnxor(b_c)
elif parity == 'pE': t += b_lxor(b_c)
t += b_c
if parity == 'sO': t += b_lnxor(b_c)
elif parity == 'sE': t += b_lxor(b_c)
t += suffix
return t
# }}} End of str_to_b()
def bytes_to_b(inbytes='', char_width=8, endian='big', prefix='', suffix='', parity='N'): # {{{
'''
Convert an byte sequence into a string of binary digits.
When used in Python 2.x, where there is no support for bytes type this will
simply return str_to_b().
This should allow the same code to be compatible with Python 2 and 3 for reading files.
E.g. bytes_to_b(open(<filename>, 'r').read())
The bit-endianness of each character can be set with the char_width and
endian arguments although these are set to 8 bits wide and big
endian by default.
A prefix and suffix can also be specified to be added to each character.
This can be useful for simulating start and stop bits.
The parity argument can be used to add a parity bit.
The allowed options are;
N = None. No parity bit will be inserted.
pO = prefixed Odd. Odd parity bit will be prefixed to sequence.
sO = suffixed Odd. Odd parity bit will be suffixed to character.
pE = prefixed Even. Even parity bit will be prefixed to character.
sE = suffixed Even. Even parity bit will be suffixed to character.
Mark and Space parity bits can be included with the prefix and suffix
arguments as they are always fixed to either 1 or 0.
E.g. bytes_to_b() returns ''
bytes_to_b(b'\\x00') returns '00000000'
bytes_to_b(b'abc') returns '011000010110001001100011'
bytes_to_b(b'U') returns '01010101'
bytes_to_b(b'U', endian='little') returns '10101010'
bytes_to_b(b'U', char_width=7) returns '1010101'
bytes_to_b(b'U', prefix='1111', suffix='0000') returns '1111010101010000'
bytes_to_b(b'\\x00', parity='pO') returns '100000000'
bytes_to_b(b'U', parity='sE') returns '010101010'
'''
assert type(endian) is str, \
'Invalid type : endian : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(endian)),
}
assert endian == 'little' or endian == 'big', \
'Invalid value: endian : Expected %(expect)s : %(actual)s' % {
'expect': '"little" OR "big"',
'actual': str(endian),
}
assert type(char_width) is int, \
'Invalid type : char_width : Expected %(expect)s : %(actual)s' % {
'expect': str(type(int())),
'actual': str(type(char_width)),
}
assert char_width >= 0, \
'Invalid value : char_width : Expected %(expect)s : %(actual)s' % {
'expect': 'char_width >= 0',
'actual': str(char_width),
}
assert type(parity) is str, \
'Invalid type : parity : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(parity)),
}
assert parity == 'N' or \
parity == 'pO' or \
parity == 'sO' or \
parity == 'pE' or \
parity == 'sE', \
'Invalid value: prefix : Expected %(expect)s : %(actual)s.' % {
'expect': '"N" OR "pO" OR "sO" OR "pE" OR "sE"',
'actual': str(prefix),
}
assert b_validate(prefix, fail_empty=False) == True, \
'Invalid b_string : prefix : %(actual)s' % {'actual': str(prefix)}
assert b_validate(suffix, fail_empty=False) == True, \
'Invalid b_string : suffix : %(actual)s' % {'actual': str(suffix)}
if type(inbytes) is str:
return str_to_b(instr=inbytes, char_width=char_width, endian=endian, prefix=prefix, suffix=suffix, parity=parity)
else:
assert type(inbytes) is bytes, \
'Invalid type : inbytes : Expected %(expect)s : %(actual)s' % {
'expect': str(type(bytes())),
'actual': str(type(inbytes)),
}
t = ''
for i, b in enumerate(inbytes):
assert int(b) < 256, \
'Invalid value : byte "%(b)s" at position %(i)s is not a valid byte (< 256)' % {
'b': str(b),
'i': str(i),
}
b_c = int_to_b(int(b), width=char_width, endian=endian, chop='most')
t += prefix
if parity == 'pO': t += b_lnxor(b_c)
elif parity == 'pE': t += b_lxor(b_c)
t += b_c
if parity == 'sO': t += b_lnxor(b_c)
elif parity == 'sE': t += b_lxor(b_c)
t += suffix
return t
# }}} End of bytes_to_b()
def baseX_to_b(instr='A', base=64, alphabet='', pad='='): # {{{
'''
Convert from another base to binary coding.
This is performs to opposite function to b_to_baseX().
The input base can be either 4, 8, 16, 32 or 64 (default).
A user-defined alphabet can be supplied containing any characters in any
order as long at the length is equal to the base using the alphabet
argument.
Supplying an empty input string will return in the alphabet which is used
for that base.
The default alphabets for bases 32 and 64 are taken from RCF 3548 and
the alphabets used for bases 4, 8 and 16 are standard.
If a character is used in the input string it must be specified using the
pad argument.
E.g. baseX_to_b() returns '000000'
baseX_to_b('') returns 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
baseX_to_b('', base=4) returns '0123'
baseX_to_b('', base=8) returns '01234567'
baseX_to_b('', base=16) returns '0123456789ABCDEF'
baseX_to_b('', base=32) returns 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
baseX_to_b('', base=64) returns 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
baseX_to_b('0123', base=4) returns '00011011'
baseX_to_b('01234567', base=8) returns '000001010011100101110111'
baseX_to_b('05AF', base=16) returns '0000010110101111'
baseX_to_b('AZ27', base=32) returns '00000110011101011111'
baseX_to_b('TWFu', base=64) returns '010011010110000101101110'
'''
# These are the default alphabets.
# 4 is standard radix-4 notation.
# 8 is standard octal notation.
# 16 is standard hexadecimal notation (uppercase). This also appears in RFC 3548.
# 32 and 64 are taken from RFC 3548.
base_alphabets = {
'4' : '0123',
'8' : '01234567',
'16' : '0123456789ABCDEF',
'32' : 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
'64' : 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
}
assert type(base) is int, \
'Invalid type : base : Expected %(expect)s : %(actual)s' % {
'expect': str(type(int())),
'actual': str(type(base)),
}
assert base in [4, 8, 16, 32, 64], \
'Invalid value: base : Expected %(expect)s : %(actual)s' % {
'expect': '4 OR 8 OR 16 OR 32 OR 64',
'actual': str(base),
}
assert type(pad) is str, \
'Invalid type : pad : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(pad)),
}
assert len(pad) <= 1, \
'Invalid value: pad : Expected %(expect)s : %(actual)s' % {
'expect': 'len(pad) <= 1',
'actual': str(len(pad)),
}
assert type(alphabet) is str, \
'Invalid type : alphabet : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(alphabet)),
}
if not len(alphabet): alphabet = base_alphabets[str(base)] # Allow user to specify their own alphabet else use default.
assert len(alphabet) == base, \
'Invalid value: alphabet : Expected %(expect)s : %(actual)s' % {
'expect': 'len(alphabet) == base',
'actual': str(len(alphabet)),
}
assert type(instr) is str, \
'Invalid type : instr : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(instr)),
}
# Return the active alphabet on empty input string.
if not len(instr): return alphabet
if len(pad): instr = instr.rstrip(pad) # Remove padding characters
# Validate instr
from re import compile as re_compile
pattern = re_compile('[^' + alphabet + ']')
assert bool(pattern.search(instr)) == False, \
'Invalid value: instr : Contains characters not in given alphabet'
del re_compile, pattern
from math import log
bits_per_char = int(log(base, 2)) # Calculate the number of bits each character will represent.
del log
# Generate string of new base.
t = ''
for c in instr: t += int_to_b(alphabet.find(c), width=bits_per_char)
return t
# }}} End of baseX_to_b()
# }}} End of Convertions To Binary Strings
# Convertions From Binary Strings {{{
def b_to_int(A='0', endian='big'): # {{{
'''
Convert binary string of digits to an integer.
The endianess is big by default but can be set to little to return a
bit reversal.
This is basically just a wrapper for the inbuilt Python function int()
which is defined for completeness.
E.g. b_to_int('00000000') returns 0
b_to_int('0101') returns 5
b_to_int('0101', endian='little') returns 10
'''
assert b_validate(A) == True, \
'Invalid b_string : A : %(actual)s' % {'actual': str(A)}
assert type(endian) is str, \
'Invalid type : endian : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(endian)),
}
assert endian == 'little' or endian == 'big', \
'Invalid value: endian : Expected %(expect)s : %(actual)s' % {
'expect': '"little" OR "big"',
'actual': str(endian),
}
t = ''
if endian == 'big': t = A
else: t = A[::-1]
return int(t, 2)
# }}} End of b_to_int()
def b_to_frac(A='0', endian='big'): # {{{
'''
Convert a binary string to a positive float which is less than 1.0.
The endianess is little by default but can be set to big to return a
bit reversal.
E.g. b_to_frac('00000000') returns 0.0
b_to_frac('0101') returns 0.3125
'''
assert b_validate(A) == True, \
'Invalid b_string : A : %(actual)s' % {'actual': str(A)}
assert type(endian) is str, \
'Invalid type : endian : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(endian)),
}
assert endian == 'little' or endian == 'big', \
'Invalid value: endian : Expected %(expect)s : %(actual)s' % {
'expect': '"little" OR "big"',
'actual': str(endian),
}
if endian == 'little': A = A[::-1]
t = 0.0
for i, b in enumerate(A):
if b == '1': t += 1.0 / 2**(i+1)
return t
# }}} End of b_to_frac()
def b_to_str(A='', align='left', b_pad='0'): # {{{
'''
Convert a b_string to an ASCII string suitable for writing to a file in
binary mode.
The input will be padded to a multiple of 8 bits long and can be controlled
with the arguments align and b_pad.
E.g. b_to_str() returns ''
b_to_str('') returns ''
b_to_str('0') returns '\\x00'
b_to_str('1') returns '\\x80'
b_to_str('01010101') returns 'U'
b_to_str('011000010110001001100011') returns 'abc'
b_to_str('0110000101100010011000111') returns 'abc\\x80'
'''
assert b_validate(A, fail_empty=False) == True, \
'Invalid b_string : A : %(actual)s' % {'actual': str(A)}
assert type(align) is str, \
'Invalid type : align : Expected %(expect)s : %(actual)s' % {
'expect': str(type(str())),
'actual': str(type(align)),
}
assert align == 'right' or align == 'left', \
'Invalid value: align : Expected %(expect)s : %(actual)s' % {
'expect': '"left" OR "right"',
'actual': str(align),
}