MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / hexToDecimal

Function hexToDecimal

conversion/hexadecimaltodecimal.go:23–57  ·  view source on GitHub ↗

hexToDecimal converts a hexadecimal string to a decimal integer.

(hexStr string)

Source from the content-addressed store, hash-verified

21
22// hexToDecimal converts a hexadecimal string to a decimal integer.
23func hexToDecimal(hexStr string) (int64, error) {
24
25 hexStr = strings.TrimSpace(hexStr)
26
27 if len(hexStr) == 0 {
28 return 0, fmt.Errorf("input string is empty")
29 }
30
31 // Check if the string has a valid hexadecimal prefix
32 if len(hexStr) > 2 && (hexStr[:2] == "0x" || hexStr[:2] == "0X") {
33 hexStr = hexStr[2:]
34 }
35
36 // Validate the hexadecimal string
37 if !isValidHexadecimal(hexStr) {
38 return 0, fmt.Errorf("invalid hexadecimal string")
39 }
40
41 var decimalValue int64
42 for _, char := range hexStr {
43 var digit int64
44 if char >= '0' && char <= '9' {
45 digit = int64(char - '0')
46 } else if char >= 'A' && char <= 'F' {
47 digit = int64(char - 'A' + 10)
48 } else if char >= 'a' && char <= 'f' {
49 digit = int64(char - 'a' + 10)
50 } else {
51 return 0, fmt.Errorf("invalid character in hexadecimal string: %c", char)
52 }
53 decimalValue = decimalValue*16 + digit
54 }
55
56 return decimalValue, nil
57}

Callers 2

TestHexToDecimalFunction · 0.85
BenchmarkHexToDecimalFunction · 0.85

Calls

no outgoing calls

Tested by 2

TestHexToDecimalFunction · 0.68
BenchmarkHexToDecimalFunction · 0.68