Skip to content

Commit a0c531b

Browse files
committed
switch representation of bit-vectors to hex
Simultaneously leading zeros are dropped. This reduces the memory consumption of bit-vectors by 4x or more.
1 parent 9b9895a commit a0c531b

File tree

1 file changed

+39
-3
lines changed

1 file changed

+39
-3
lines changed

src/util/mp_arith.cpp

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -186,17 +186,53 @@ const mp_integer binary2integer(const std::string &n, bool is_signed)
186186
}
187187

188188
/// convert an integer to bit-vector representation with given width
189+
/// This uses two's complement for negative numbers.
190+
/// If the value is out of range, it is 'wrapped around'.
189191
const std::string integer2bv(const mp_integer &src, std::size_t width)
190192
{
191-
return integer2binary(src, width);
193+
const mp_integer p = power(2, width);
194+
195+
if(src.is_negative())
196+
{
197+
// do two's complement encoding of negative numbers
198+
mp_integer tmp = src;
199+
tmp.negate();
200+
tmp %= p;
201+
if(tmp != 0)
202+
tmp = p - tmp;
203+
return integer2string(tmp, 16);
204+
}
205+
else
206+
{
207+
// we 'wrap around' if 'src' is too large
208+
return integer2string(src % p, 16);
209+
}
192210
}
193211

194212
/// convert a bit-vector representation (possibly signed) to integer
195213
const mp_integer
196214
bv2integer(const std::string &src, std::size_t width, bool is_signed)
197215
{
198-
PRECONDITION(src.size() == width);
199-
return binary2integer(src, is_signed);
216+
if(is_signed)
217+
{
218+
PRECONDITION(width >= 1);
219+
const auto tmp = string2integer(src, 16);
220+
const auto p = power(2, width - 1);
221+
if(tmp >= p)
222+
{
223+
const auto result = tmp - 2 * p;
224+
PRECONDITION(result >= -p);
225+
return result;
226+
}
227+
else
228+
return tmp;
229+
}
230+
else
231+
{
232+
const auto result = string2integer(src, 16);
233+
PRECONDITION(result < power(2, width));
234+
return result;
235+
}
200236
}
201237

202238
mp_integer::ullong_t integer2ulong(const mp_integer &n)

0 commit comments

Comments
 (0)