2016-09-08 11:39:08 +00:00
|
|
|
package hexadecimal
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
func ParseHex(in string) (int64, error) {
|
|
|
|
return convertNumStringBase(in, int64(16))
|
|
|
|
}
|
|
|
|
|
|
|
|
func HandleErrors(in []string) []string {
|
|
|
|
var ret []string
|
|
|
|
for i := range in {
|
2016-09-09 16:24:29 +00:00
|
|
|
errStr := "none"
|
2016-09-08 11:39:08 +00:00
|
|
|
_, err := convertNumStringBase(in[i], 16)
|
2016-09-09 16:24:29 +00:00
|
|
|
if err != nil {
|
|
|
|
errStr = err.Error()
|
|
|
|
}
|
|
|
|
ret = append(ret, errStr)
|
2016-09-08 11:39:08 +00:00
|
|
|
}
|
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
|
|
|
// convertNumStringBase takes a numeric string and the base of that string
|
|
|
|
// and returns an int64 of the decimal representation
|
2016-09-09 16:24:29 +00:00
|
|
|
func convertNumStringBase(in string, base int64) (int64, error) {
|
2016-09-08 11:39:08 +00:00
|
|
|
if in == "" {
|
|
|
|
return 0, errors.New("syntax")
|
|
|
|
}
|
|
|
|
in = strings.ToLower(in)
|
2016-09-09 16:24:29 +00:00
|
|
|
var a, n int64
|
2016-09-08 11:39:08 +00:00
|
|
|
for i := range in {
|
2016-09-09 16:24:29 +00:00
|
|
|
n *= base
|
|
|
|
switch {
|
|
|
|
case in[i] >= '0' && in[i] <= '9':
|
|
|
|
a = int64(in[i] - '0')
|
|
|
|
case in[i] >= 'a' && in[i] <= 'f':
|
|
|
|
a = int64(in[i]-'a') + 10
|
|
|
|
default:
|
|
|
|
return 0, errors.New("syntax")
|
2016-09-08 11:39:08 +00:00
|
|
|
}
|
2016-09-09 16:24:29 +00:00
|
|
|
if a > base {
|
2016-09-08 11:39:08 +00:00
|
|
|
return 0, errors.New("syntax")
|
|
|
|
}
|
2016-09-09 16:24:29 +00:00
|
|
|
n += a
|
2016-09-08 11:39:08 +00:00
|
|
|
|
2016-11-14 13:56:52 +00:00
|
|
|
if n <= 0 && in[0] != '0' {
|
2016-09-09 16:24:29 +00:00
|
|
|
return 0, errors.New("range")
|
2016-09-08 11:39:08 +00:00
|
|
|
}
|
|
|
|
}
|
2016-09-09 16:24:29 +00:00
|
|
|
return n, nil
|
2016-09-08 11:39:08 +00:00
|
|
|
}
|