Skip to content

Commit 65a9ad3

Browse files
committed
add base_I op that converts a bigint to a string with a given base
1 parent 945817d commit 65a9ad3

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

src/PAST/NQP.pir

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -565,6 +565,7 @@ entry to produce the node to be returned.
565565
# bigint ops
566566
maphash['fromstr_I'] = 'nqp_bigint_from_str__PPs'
567567
maphash['tostr_I'] = 'nqp_bigint_to_str__SP'
568+
maphash['base_I'] = 'nqp_bigint_to_str_base__SPI'
568569
maphash['isbig_I'] = 'nqp_bigint_is_big__IP'
569570
maphash['fromnum_I'] = 'nqp_bigint_from_num__PNP'
570571
maphash['tonum_I'] = 'nqp_bigint_to_num__NP'

src/ops/nqp_bigint.ops

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,18 @@ inline op nqp_bigint_to_str(out STR, in PMC) :base_core {
270270
mem_sys_free(buf);
271271
}
272272

273+
inline op nqp_bigint_to_str_base(out STR, in PMC, in INT) :base_core {
274+
mp_int *i = get_bigint(interp, $2);
275+
int len;
276+
char *buf;
277+
mp_radix_size(i, $3, &len);
278+
buf = mem_sys_allocate(len);
279+
mp_toradix_n(i, buf, $3, len);
280+
/* len - 1 because buf is \0-terminated */
281+
$1 = Parrot_str_new(interp, buf, len - 1);
282+
mem_sys_free(buf);
283+
}
284+
273285
inline op nqp_bigint_to_num(out NUM, in PMC) :base_core {
274286
mp_int *a = get_bigint(interp, $2);
275287
$1 = mp_get_double(a);

t/nqp/60-bigint.t

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#! nqp
22
use nqpmo;
33

4-
plan(28);
4+
plan(30);
55

66
my $knowhow := pir::get_knowhow__P();
77
my $bi_type := $knowhow.new_type(:name('TestBigInt'), :repr('P6bigint'));
@@ -82,3 +82,5 @@ $float := -$float;
8282
ok(nqp::iseq_n($float, nqp::tonum_I(nqp::fromnum_I($float, $bi_type))),
8383
'to_num and from_num round-trip (negative number)');
8484

85+
ok(nqp::base_I(box(-1234), 10) eq '-1234', 'base_I with base 10');
86+
ok(nqp::base_I(box(-1234), 16) eq '-4D2', 'base_I with base 16');

0 commit comments

Comments
 (0)