Skip to content

Commit

Permalink
handle empty hex string (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
hewigovens authored Jan 24, 2021
1 parent 617190e commit 98c4cbf
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 10 deletions.
3 changes: 3 additions & 0 deletions numbers/decimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ func DecimalExp(dec string, exp int) string {
// HexToDecimal converts a hexadecimal integer to a base-10 integer
// "0x1fbad5f2e25570000" => "36582000000000000000"
func HexToDecimal(hex string) (string, error) {
if len(hex) == 0 || hex == "0x" {
return "0", nil
}
var i big.Int
if _, ok := i.SetString(hex, 0); !ok {
return "", errors.New("invalid hex: " + hex)
Expand Down
35 changes: 25 additions & 10 deletions numbers/decimal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,25 +115,40 @@ func TestCutZeroFractional(t *testing.T) {
}

func TestHexToDecimal(t *testing.T) {
type args struct {
hex string
}
tests := []struct {
name string
args args
hex string
want string
wantErr bool
}{
{
"Hex to decimal",
args{hex: "0x1fbad5f2e25570000"},
"36582000000000000000",
false,
name: "Empty value",
hex: "",
want: "0",
wantErr: false,
},
{
name: "Empty value 2",
hex: "0x",
want: "0",
wantErr: false,
},
{
name: "Empty value 3",
hex: "0x0",
want: "0",
wantErr: false,
},
{
name: "Hex to decimal",
hex: "0x1fbad5f2e25570000",
want: "36582000000000000000",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := HexToDecimal(tt.args.hex)
got, err := HexToDecimal(tt.hex)
if (err != nil) != tt.wantErr {
t.Errorf("HexToDecimal() error = %v, wantErr %v", err, tt.wantErr)
return
Expand All @@ -143,4 +158,4 @@ func TestHexToDecimal(t *testing.T) {
}
})
}
}
}

0 comments on commit 98c4cbf

Please sign in to comment.