【发布时间】:2023-03-30 07:34:01
【问题描述】:
我有 16 个十六进制值,我需要计算位(1)的总数
#I have tried this
val = hex(bus.read_port(0))+hex(bus.read_port(1)) #There are 16 ports.
#read port returns a Decimal (0-255)
#val is 0x3f0xff
def bitCount(val):
count = bin(val).count('1')
return (count)
#bitCount() Returns 6 instead of 14
但它只返回第一个字节的位。 在返回之前打印 val 例如0x3f0xff 我需要的是 3F00FF (每个十六进制的二进制值串成一个十六进制) 或另一种读取组合位数的方式。
这似乎可行,但我得到 10 而不是 16
bus.write_port(0, 0xFF)
bus.write_port(1, 0xFF)
def popcount255(k):
k = (k & 15) + (k >> 4)
k = (k & 3) + (k >> 2)
return (k & 1) + (k >> 1)
def bitCount():
result = popcount255(bus.read_port(0)) + popcount255(bus.read_port(1))
return (result)
if True:
print "BitCount ", bitCount()
我数到了 10?
现在可以使用了
def bitCount():
result = bin(bus_1.read_port(0)).count('1') + bin(bus_1.read_port(1)).count('1')
return (result)
【问题讨论】:
-
好吧
0x3f0xff没有任何意义。 -
将原始问题备份起来对您很有帮助,然后是您的其他代码和有关使 @WillemVanOnsem 的方法起作用的问题。