Binary Patterns with Python

The study of pattern identification requires the identification of repeating patterns in binary representations of fractions of rational numbers. bin(2**24/n) separates leading zeros , for example. bin(2**24/11)โ†’ 0b101110100010111010001instead 0b000101110100010111010001. Of course, the number of leading zeros varies. The obvious point here is 0001011101 ...

I'm a nubee with Python still on a learning curve. Is there any Python-friendly way to approach this?

+3
source share
2 answers

You may find the bitstring module useful if you have more complex needs than string formatting can be.

>>> from bitstring import BitArray
>>> a = BitArray(24)          # 24 zero bits
>>> a.uint = 2**24/11         # set the unsigned integer propery
>>> a.bin                     # get the binary propery
'000101110100010111010001'

It never truncates the initial zero bits and can do some more useful tricks.

>>> a.uint /= 2
>>> a.bin
'000010111010001011101000'
>>> list(a.findall('0b1011'))
[4, 14]
>>> a *= 2     # concatenation
>>> a.bin
'000010111010001011101000000010111010001011101000'
>>> a.replace('0b00001', '0xe')
2              # 2 replacements made
>>> a.bin
'1110011101000101110100011100111010001011101000'

I'm not sure about your specific needs, so all this can be excessive, and you can not use an external library in any case, but the built-in Python support for bit arrays is a bit basic.

+2
source

This can be done with string formatting, in 2.6+:

>>> '{0:024b}'.format(23)
'000000000000000000010111'
+4
source

Source: https://habr.com/ru/post/1774157/


All Articles