Skip to content Skip to sidebar Skip to footer

Logical Or For Bit-string In Python

What i want to do is have the result of logical OR for two bit-strings. For example: a='010010' b='000101' c=LOGIC_OR(a,b) c 010111 The error i encounter most

Solution 1:

You can convert them to integers with int specifying the base to be 2. Then, perform a bitwise OR operation and convert the result to a bit string with bin.

>>>c = int(a, 2) | int(b, 2))>>>c
23

If you want to print the result as a bit string, use str.format. If you're on python-3.6, you can also use f-strings.

>>> '{:b}'.format(c)
'10111'

>>>print(f"{c:b}")
10111

To capture leading zeros with respect to a/b, use str.zfill -

>>> f"{c:b}".zfill(len(a))
'010111'

Solution 2:

Here are a couple of alternative methods.

Third-party bitarray library:

from bitarray import bitarray

a='010010'
b='000101'

logical_or_bitarray = bitarray(a) | bitarray(b)  # output: bitarray('010111')
logical_or_string = ''.join(map(str, map(int, logical_or_bitarray)))  # output: '010111'

Python strings:-

a='010010'
b='000101'defcompare_bits(A, B):
    c_1 = str(int(A) | int(B))
    c = (len(A) - len(c_1))*'0' + str(c_1)
    return c

compare_bits(a, b)

Solution 3:

You should convert to int objects and do numerical operations in the numerical data type. Then you use string-formatting when you need to see it. If you have Python 3.6, using f-strings makes this trivial:

>>>a='010010'>>>b='000101'>>>a = int(a, base=2) # we should be ints>>>b = int(b, base=2) # we should be ints>>>c = a | b # operations natural and built in>>>print(f"{c:b}") # use formatting when you need it
10111

Read the string formatting spec's. You can make them do whatever you desire. Using a fill value of '0' and a width of '6':

>>>print(f"{c:0>6b}")
010111

And this is cool too:

>>>pad='0'>>>width = 6>>>print(f"{c:{pad}>{width}b}")
010111

Post a Comment for "Logical Or For Bit-string In Python"