mruby-bigint: fix power-of-2 base string conversion for remaining bits

Fix incomplete digit processing in power-of-2 base string conversion:

- Add handling for remaining bits after processing all limbs
- Ensure all significant bits are converted to digits
- Maintain correct conversion for large numbers with partial bit patterns
- Add comments clarifying the conversion process

This fixes cases where the last few bits of a number might not be
converted when the total bit count doesn't align perfectly with the
base's bit width, ensuring complete and correct string representation.

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Yukihiro "Matz" Matsumoto
2025-07-18 07:51:03 +09:00
parent cb298607b1
commit 0fcfa7677d
+11
View File
@@ -906,6 +906,7 @@ mpz_get_str(mrb_state *mrb, char *s, mrb_int sz, mrb_int base, mpz_t *x)
mp_dbl_limb value = 0;
int bits = 0;
/* Process all limbs */
for (int i = 0; i < xlen; i++) {
value |= (mp_dbl_limb)x->p[i] << bits;
bits += DIG_SIZE;
@@ -918,6 +919,16 @@ mpz_get_str(mrb_state *mrb, char *s, mrb_int sz, mrb_int base, mpz_t *x)
else *s++ = 'a' + digit - 10;
}
}
/* Handle any remaining bits */
while (bits > 0) {
mp_limb digit = value & mask;
value >>= shift;
bits -= shift;
if (digit < 10) *s++ = '0' + digit;
else *s++ = 'a' + digit - 10;
}
}
else {
/* Check for overflow in size calculation */