diff --git a/vlib/math/big/big.v b/vlib/math/big/big.v index 453e59131a..67cbc38aa9 100644 --- a/vlib/math/big/big.v +++ b/vlib/math/big/big.v @@ -93,7 +93,13 @@ pub fn from_u64(u u64) Number { } // Converts a hex string to big.Number. -pub fn from_string(s string) Number { +pub fn from_string(input string) Number { + mut s := input.trim_prefix('0x') + if s.len == 0 { + s = '0' + } + padding := '0'.repeat((8 - s.len % 8) % 8) + s = padding + s n := Number{} C.bignum_from_string(&n, s.str, s.len) return n diff --git a/vlib/math/big/big_test.v b/vlib/math/big/big_test.v index 418863093e..da550160d1 100644 --- a/vlib/math/big/big_test.v +++ b/vlib/math/big/big_test.v @@ -77,6 +77,19 @@ fn test_mod() { assert (big.from_u64(7) % big.from_u64(5)).int() == 2 } +fn test_from_str() { + assert big.from_string('').hexstr() == '0' + assert big.from_string('1').hexstr() == '1' + assert big.from_string('0').hexstr() == '0' + assert big.from_string('0x123').hexstr() == '123' + for i in 1 .. 33 { + input := 'e'.repeat(i) + out := big.from_string(input).hexstr() + assert input == out + } + assert big.from_string('0').hexstr() == '0' +} + fn test_str() { assert big.from_u64(255).str() == '255' assert big.from_u64(127).str() == '127'