简体   繁体   English

二进制字符串python的按位运算

[英]Bitwise operation on Binary string python

If I have two strings of binary representation.如果我有两个二进制表示的字符串。 How to do bitwise on them?如何按位对它们进行处理?

Example例子

a = '101'
b = '010'
c = a | b
c => '111'

First, use int to convert the binary strings to numbers.首先,使用int将二进制字符串转换为数字。 You can use the second parameter of int to specify the base, 2 in this case.您可以使用int第二个参数来指定基数,在本例中为 2。 Then, you can use |然后,您可以使用| to "or" the numbers and bin or a format-string (many different possibilities here) to convert back to binary. “或”数字和bin或格式字符串(此处有许多不同的可能性)以转换回二进制。

>>> a = '101'
>>> b = '010'
>>> c = int(a, 2) | int(b, 2)
>>> bin(c)
'0b111'
>>> f"{c:b}"
'111'
>>> format(c, "b")
'111'

The latter two can also be used to add any number of leading zeros, if necessary, eg using 08b instead of b in the format string.如有必要,后两者还可用于添加任意数量的前导零,例如在格式字符串中使用08b代替b

A solution that works on the strings (not via ints) and keeps leading zeros intact:适用于字符串(不是通过整数)并保持前导零不变的解决方案:

>>> a = '0101'
>>> b = '0011'
>>> ''.join(map(max, a, b))
'0111'

Needs the strings to have equal length, but given your example where one string has a leading zero so it's as long as the other, I guess that's the case for you.需要字符串具有相等的长度,但是鉴于您的示例,其中一个字符串的前导零因此与另一个字符串一样长,我想您就是这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM