@@ -185,11 +185,47 @@ const mp_integer binary2integer(const std::string &n, bool is_signed)
185
185
#endif
186
186
}
187
187
188
+ #define B256
189
+
190
+ #ifdef B256
191
+ std::string dump_integer (mp_integer src)
192
+ {
193
+ std::size_t d = src.digits (256 ) + 1 ;
194
+ unsigned char *buf = new unsigned char [d], *p = buf;
195
+ src.dump (buf, d);
196
+ while (d > 0 && *p == 0 )
197
+ {
198
+ d--;
199
+ p++;
200
+ }
201
+ return std::string ((char *)p, d);
202
+ }
203
+ #endif
204
+
188
205
// / convert an integer to bit-vector representation with given width
189
206
// / This uses two's complement for negative numbers.
190
207
// / If the value is out of range, it is 'wrapped around'.
191
208
const std::string integer2bv (const mp_integer &src, std::size_t width)
192
209
{
210
+ #ifdef B256
211
+ const mp_integer p = power (2 , width);
212
+
213
+ if (src.is_negative ())
214
+ {
215
+ // do two's complement encoding of negative numbers
216
+ mp_integer tmp = src;
217
+ tmp.negate ();
218
+ tmp %= p;
219
+ if (tmp != 0 )
220
+ tmp = p - tmp;
221
+ return dump_integer (tmp);
222
+ }
223
+ else
224
+ {
225
+ // we 'wrap around' if 'src' is too large
226
+ return dump_integer (src % p);
227
+ }
228
+ #else
193
229
const mp_integer p = power (2 , width);
194
230
195
231
if (src.is_negative ())
@@ -207,12 +243,37 @@ const std::string integer2bv(const mp_integer &src, std::size_t width)
207
243
// we 'wrap around' if 'src' is too large
208
244
return integer2string (src % p, 16 );
209
245
}
246
+ #endif
210
247
}
211
248
212
249
// / convert a bit-vector representation (possibly signed) to integer
213
250
const mp_integer
214
251
bv2integer (const std::string &src, std::size_t width, bool is_signed)
215
252
{
253
+ #ifdef B256
254
+ if (is_signed)
255
+ {
256
+ PRECONDITION (width >= 1 );
257
+ mp_integer tmp;
258
+ tmp.load ((const unsigned char *)src.data (), src.size ());
259
+ const auto p = power (2 , width - 1 );
260
+ if (tmp >= p)
261
+ {
262
+ const auto result = tmp - 2 * p;
263
+ PRECONDITION (result >= -p);
264
+ return result;
265
+ }
266
+ else
267
+ return tmp;
268
+ }
269
+ else
270
+ {
271
+ mp_integer result;
272
+ result.load ((const unsigned char *)src.data (), src.size ());
273
+ PRECONDITION (result < power (2 , width));
274
+ return result;
275
+ }
276
+ #else
216
277
if (is_signed)
217
278
{
218
279
PRECONDITION (width >= 1 );
@@ -233,6 +294,7 @@ bv2integer(const std::string &src, std::size_t width, bool is_signed)
233
294
PRECONDITION (result < power (2 , width));
234
295
return result;
235
296
}
297
+ #endif
236
298
}
237
299
238
300
mp_integer::ullong_t integer2ulong (const mp_integer &n)
0 commit comments