Sum of all the bits in a Bit Vector of Z3

落爺英雄遲暮 提交于 2019-12-01 02:10:00
Nikolaj Bjorner

It isn't part of the bit-vector operations. You can create an expression as follows:

def sub(b):
    n = b.size()
    bits = [ Extract(i, i, b) for i in range(n) ]
    bvs  = [ Concat(BitVecVal(0, n - 1), b) for b in bits ]
    nb   = reduce(lambda a, b: a + b, bvs)
    return nb


print sub(BitVecVal(4,7))

Of course, log(n) bits for the result will suffice if you prefer.

The page:

https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive

has various algorithms for counting the bits; which can be translated to Z3/Python with relative ease, I suppose.

My favorite is: https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan

which has the nice property that it loops as many times as there are set bits in the input. (But you shouldn't extrapolate from that to any meaningful complexity metric, as you do arithmetic in each loop, which might be costly. The same is true for all these algorithms.)

Having said that, if your input is fully symbolic, you can't really beat the simple iterative algorithm, as you can't short-cut the iteration count. Above methods might work faster if the input has concrete bits.

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