Logical OR for Bit-string in Python

|▌冷眼眸甩不掉的悲伤 提交于 2020-12-13 03:17:04

问题


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 of the time is when I convert 'b' from string to binary it removes leading zeros. Others methods i have used convert 'a' and 'b' to integers. Generally nothing is working and help would be much appreciated. Thanks in advance


回答1:


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'

def compare_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)



回答2:


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'



回答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


来源:https://stackoverflow.com/questions/48373554/logical-or-for-bit-string-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!