Sum of all the bits in a Bit Vector of Z3

≡放荡痞女 提交于 2019-12-30 07:43:52

问题


Given a bit vector in Z3, I am wondering how can I sum up each individual bit of this vector?

E.g.,

a = BitVecVal(3, 2)
sum_all_bit(a) = 2

Is there any pre-implemented APIs/functions that support this? Thank you!


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/39299015/sum-of-all-the-bits-in-a-bit-vector-of-z3

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