二进制数python 2.7的字符串表示形式的按位运算 [英] bitwise operation on string representation of binary number python 2.7
本文介绍了二进制数python 2.7的字符串表示形式的按位运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想对两个二进制数字的字符串表示形式进行按位或运算,但是我不知道如何将字符串转换为原始二进制.
I would like to perform a bitwise OR on two string representations of binary numbers, but I can't figure out how to convert the strings into raw binary.
a ='010110'
b ='100000'
a = '010110'
b = '100000'
a |b
应产生:110110
should yield: 110110
然后我要计算开启位数.
这应该返回:
4
I then want to count the number of on bits.
This should return:
4
推荐答案
You can convert the strings to binary using the built-in int() function and passing 2 as the base:
a = int('010110', 2)
b = int('100000', 2)
然后对这两个值进行或运算,并通过转换为字符串并计算"1"字符来对位数进行计数:
then OR the two values and count the bits by converting to a string and counting the "1" characters:
print bin(a | b).count("1")
这篇关于二进制数python 2.7的字符串表示形式的按位运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文