57 lines
1.2 KiB
Go
57 lines
1.2 KiB
Go
package hexadecimal
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"math/big"
|
|
"strings"
|
|
)
|
|
|
|
func ParseHex(in string) (int64, error) {
|
|
return convertNumStringBase(in, int64(16))
|
|
}
|
|
|
|
func HandleErrors(in []string) []string {
|
|
var ret []string
|
|
for i := range in {
|
|
_, err := convertNumStringBase(in[i], 16)
|
|
ret = append(ret, err.Error())
|
|
}
|
|
return ret
|
|
}
|
|
|
|
// convertNumStringBase takes a numeric string and the base of that string
|
|
// and returns an int64 of the decimal representation
|
|
func convertNumStringBase(in string, oldBase int64) (int64, error) {
|
|
if in == "" {
|
|
return 0, errors.New("syntax")
|
|
}
|
|
in = strings.ToLower(in)
|
|
base := big.NewInt(oldBase)
|
|
var sum big.Int
|
|
for i := range in {
|
|
var x *big.Int
|
|
if in[i] >= '0' && in[i] <= '9' {
|
|
x = big.NewInt(int64(in[i] - '0'))
|
|
} else if in[i] >= 'a' && in[i] <= 'z' {
|
|
x = big.NewInt(int64(in[i]-'a') + 10)
|
|
}
|
|
fmt.Println("Comparing Converted Value ", x, "<", oldBase)
|
|
if x.Int64() > oldBase {
|
|
return 0, errors.New("syntax")
|
|
}
|
|
|
|
pow := big.NewInt(int64(len(in) - i - 1))
|
|
|
|
var n big.Int
|
|
n.Exp(base, pow, nil)
|
|
n.Mul(x, &n)
|
|
|
|
sum.Add(&sum, &n)
|
|
if sum.Int64() < 0 {
|
|
return 0, errors.New("Integer Overflow")
|
|
}
|
|
}
|
|
return sum.Int64(), nil
|
|
}
|