math.big: fix bytes() if bit_len is divisible by 60, add tests (#25126)

This commit is contained in:
Mike 2025-08-17 19:25:15 +03:00 committed by GitHub
parent a534a9fd5c
commit 51630f1795
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 16 additions and 1 deletions

View file

@ -991,3 +991,14 @@ fn test_pow2_is_power_of_2() {
assert big.two_int.pow(n).is_power_of_2(), 'pow2: ${n}'
}
}
fn test_bytes_from_bytes() {
input := ['0', '9999999999999999999999999999999999999', '783086277830859384',
'890810171456467012368983335296321559']
for n in input {
a := big.integer_from_string(n)!
b, _ := a.bytes()
c := big.integer_from_bytes(b)
assert a.str() == c.str()
}
}

View file

@ -891,7 +891,11 @@ pub fn (a Integer) bytes() ([]u8, int) {
bits_in_byte = 0
}
// MSB digit
for i := bit_len % digit_bits - 1; i >= 0; i-- {
mut msb_bits := bit_len % digit_bits
if msb_bits == 0 {
msb_bits = digit_bits
}
for i := msb_bits - 1; i >= 0; i-- {
bit = u8((digit >> i) & 1)
current_byte = (current_byte << 1) | u8(bit)
bits_in_byte++