-
Notifications
You must be signed in to change notification settings - Fork 6
/
big_ints.go
57 lines (45 loc) · 1.25 KB
/
big_ints.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package utils
import (
"errors"
"fmt"
"math/big"
)
var (
ErrBigIntBadBytes = errors.New("byte slice length should equal 32")
)
// BigIntsToHex encodes two big.Int pointers as a hexdecimal string.
func BigIntsToHex(a, b *big.Int) string {
bytes := BigIntsToBytes(a, b)
hex := fmt.Sprintf("%x", bytes)
return hex
}
// BigIntsToBytes encodes two big.Int pointers as a byte slice.
func BigIntsToBytes(a, b *big.Int) []byte {
bytes := append(a.Bytes(), b.Bytes()...)
return bytes
}
// BigIntsFromHex decodes two big.Int pointers from a hexdecimal string.
func BigIntsFromHex(hex string) (*big.Int, *big.Int) {
bytes := HexToBytes(hex)
halfLength := len(bytes) / 2
aBytes := bytes[:halfLength]
bBytes := bytes[halfLength:]
a, b := BigIntsFromBytes(aBytes, bBytes)
return a, b
}
// BigIntsFromBytes decodes two big.Int pointers from a byte slice.
func BigIntsFromBytes(aBytes, bBytes []byte) (*big.Int, *big.Int) {
a, err := BytesToBigInt(aBytes)
PanicError(err)
b, err := BytesToBigInt(bBytes)
PanicError(err)
return a, b
}
// BytesToBigInt decodes a big.Int pointer from a byte slice.
func BytesToBigInt(bytes []byte) (*big.Int, error) {
if len(bytes) != 32 {
return nil, ErrBigIntBadBytes
}
bi := new(big.Int).SetBytes(bytes)
return bi, nil
}