@@ -186,17 +186,53 @@ const mp_integer binary2integer(const std::string &n, bool is_signed)
186
186
}
187
187
188
188
// / 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'.
189
191
const std::string integer2bv (const mp_integer &src, std::size_t width)
190
192
{
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
+ }
192
210
}
193
211
194
212
// / convert a bit-vector representation (possibly signed) to integer
195
213
const mp_integer
196
214
bv2integer (const std::string &src, std::size_t width, bool is_signed)
197
215
{
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
+ }
200
236
}
201
237
202
238
mp_integer::ullong_t integer2ulong (const mp_integer &n)
0 commit comments