Skip to content

Commit 51630f1

Browse files
authored
math.big: fix bytes() if bit_len is divisible by 60, add tests (#25126)
1 parent a534a9f commit 51630f1

2 files changed

Lines changed: 16 additions & 1 deletion

File tree

‎vlib/math/big/big_test.v‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -991,3 +991,14 @@ fn test_pow2_is_power_of_2() {
991991
assert big.two_int.pow(n).is_power_of_2(), 'pow2: ${n}'
992992
}
993993
}
994+
995+
fn test_bytes_from_bytes() {
996+
input := ['0', '9999999999999999999999999999999999999', '783086277830859384',
997+
'890810171456467012368983335296321559']
998+
for n in input {
999+
a := big.integer_from_string(n)!
1000+
b, _ := a.bytes()
1001+
c := big.integer_from_bytes(b)
1002+
assert a.str() == c.str()
1003+
}
1004+
}

‎vlib/math/big/integer.v‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -891,7 +891,11 @@ pub fn (a Integer) bytes() ([]u8, int) {
891891
bits_in_byte = 0
892892
}
893893
// MSB digit
894-
for i := bit_len % digit_bits - 1; i >= 0; i-- {
894+
mut msb_bits := bit_len % digit_bits
895+
if msb_bits == 0 {
896+
msb_bits = digit_bits
897+
}
898+
for i := msb_bits - 1; i >= 0; i-- {
895899
bit = u8((digit >> i) & 1)
896900
current_byte = (current_byte << 1) | u8(bit)
897901
bits_in_byte++

0 commit comments

Comments
 (0)