2
votes

Is there a way to index an element in a BitVec? I'd like to something like this:

s = Solver()
x = BitVec('x', 8)
s.add(Not(And(x[0], x[2])))

Or is masking the the only way to isolate bits:

s.add(x & 5 != 5)
1

1 Answers

3
votes

You can use Extract(high, low, a) to extract one, or more, bits from a term of BitVec type.

e.g.

from z3 import *

s = Solver()
x = BitVec("x", 8)

x_0 = Extract(0, 0, x)
x_2 = Extract(2, 2, x)

expr = Or(x_0 == 0, x_2 == 0)

s.add(expr)

while s.check() == sat:
    m = s.model()
    print("Model: " + str(m))

    v_0 = m.eval(x_0)
    v_2 = m.eval(x_2)

    bl = Or(x_0 != v_0, x_2 != v_2)

    s.add(bl)

Output:

Model: [x = 4]    # 0000 0100
Model: [x = 0]    # 0000 0000
Model: [x = 1]    # 0000 0001