/
numbers.go
48 lines (40 loc) · 1.13 KB
/
numbers.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
package iotago
import (
"math/big"
"strconv"
"github.com/ethereum/go-ethereum/common/hexutil"
)
// EncodeHex encodes the bytes string to a hex string. It always adds the 0x prefix if bytes are not empty.
func EncodeHex(b []byte) string {
if len(b) == 0 {
return ""
}
return hexutil.Encode(b)
}
// DecodeHex decodes the given hex string to bytes. It expects the 0x prefix.
func DecodeHex(s string) ([]byte, error) {
b, err := hexutil.Decode(s)
if err != nil {
if err == hexutil.ErrEmptyString {
return []byte{}, nil
}
return nil, err
}
return b, nil
}
// EncodeUint256 encodes the uint256 to a little-endian encoded hex string.
func EncodeUint256(n *big.Int) string {
return hexutil.EncodeBig(n)
}
// DecodeUint256 decodes the little-endian hex encoded string to an uint256.
func DecodeUint256(s string) (*big.Int, error) {
return hexutil.DecodeBig(s)
}
// EncodeUint64 encodes the uint64 to a base 10 string.
func EncodeUint64(n uint64) string {
return strconv.FormatUint(n, 10)
}
// DecodeUint64 decodes the base 10 string to an uint64.
func DecodeUint64(s string) (uint64, error) {
return strconv.ParseUint(s, 10, 64)
}