6

I have two variables 'a' and 'b' of different size, see below. I have few questions:

(1) How can I copy value of 'a' to 'b'? (i.e extend operation)

(2) How can I copy value of 'b' to 'a'? (i.e trunc operation)

Thanks.

a = BitVec('a', 1)
b = BitVec('b', 32)
user311703
  • 1,113
  • 2
  • 14
  • 25

1 Answers1

10

For extending, we use ZeroExt or SignExt. The ZeroExt will add "zeros", and SignExt will "copy" the sign bit (i.e., the most significant bit). For truncation we use Extract, it can extract any subsequence of bits. Here is a small example (also available online at rise4fun).

a = BitVec('a', 1)
b = BitVec('b', 32)
solve(ZeroExt(31, a) == b)
solve(b > 10, Extract(0,0,b) == a)

EDIT: we can use p == (x == 1) to 'assign' a Boolean variable p with the value of a Bit-vector x of size 1, and vice-versa. The formula p == (x == 1) is just stating that p is true if and only if x is 1. Here is an example (also available online here)

x = BitVec('x', 1)
p = Bool('p')

solve(p == (x == 1), x == 0)
solve(p == (x == 1), x == 1)
solve(p == (x == 1), Not(p))
solve(p == (x == 1), p)
Leonardo de Moura
  • 21,065
  • 2
  • 47
  • 53
  • Leo, your answer is awesome! BTW, how can I 'assign' a variable of Bool type to another variable of BitVec(1) type? This is feasible, given that these two variables are actually of the same size (1 bit size). Thanks. – user311703 Jan 30 '13 at 03:07
  • The idea of having "p == (x == 1)" is great, but this can only 'assign' value of Boolean 'p', given value of BitVec(1) 'x'. How about doing the opposite: given value of 'p', set the value of 'x'? I tried to use 'Implies', but that is ugly. Do you have a better solution? Thanks. – user311703 Jan 31 '13 at 04:20
  • hmm it seems i missed the fact that "p == (x == 1)" actually does 2-way operations: given 'p', it also sets the value of 'x', respectively – user311703 Jan 31 '13 at 04:44