MCPcopy Index your code
hub / github.com/TheAlgorithms/Go / hexToBinary

Function hexToBinary

conversion/hexadecimaltobinary.go:24–78  ·  view source on GitHub ↗

hexToBinary() function that will take Hexadecimal number as string, and return its Binary equivalent as a string.

(hex string)

Source from the content-addressed store, hash-verified

22// hexToBinary() function that will take Hexadecimal number as string,
23// and return its Binary equivalent as a string.
24func hexToBinary(hex string) (string, error) {
25 // Trim any leading or trailing whitespace
26 hex = strings.TrimSpace(hex)
27
28 // Check if the hexadecimal string is empty
29 if hex == "" {
30 return "", errors.New("input string is empty")
31 }
32
33 // Check if the hexadecimal string is valid
34 if !isValidHex(hex) {
35 return "", errors.New("invalid hexadecimal string: " + hex)
36 }
37
38 // Parse the hexadecimal string to an integer
39 var decimal int64
40 for i := 0; i < len(hex); i++ {
41 char := hex[i]
42 var value int64
43 if char >= '0' && char <= '9' {
44 value = int64(char - '0')
45 } else if char >= 'A' && char <= 'F' {
46 value = int64(char - 'A' + 10)
47 } else if char >= 'a' && char <= 'f' {
48 value = int64(char - 'a' + 10)
49 } else {
50 return "", errors.New("invalid character in hexadecimal string: " + string(char))
51 }
52 decimal = decimal*16 + value
53 }
54
55 // Convert the integer to a binary string without using predefined functions
56 var binaryBuilder strings.Builder
57 if decimal == 0 {
58 binaryBuilder.WriteString("0")
59 } else {
60 for decimal > 0 {
61 bit := decimal % 2
62 if bit == 0 {
63 binaryBuilder.WriteString("0")
64 } else {
65 binaryBuilder.WriteString("1")
66 }
67 decimal = decimal / 2
68 }
69 }
70
71 // Reverse the binary string since the bits are added in reverse order
72 binaryRunes := []rune(binaryBuilder.String())
73 for i, j := 0, len(binaryRunes)-1; i < j; i, j = i+1, j-1 {
74 binaryRunes[i], binaryRunes[j] = binaryRunes[j], binaryRunes[i]
75 }
76
77 return string(binaryRunes), nil
78}

Callers 2

TestHexToBinaryFunction · 0.85
BenchmarkHexToBinaryFunction · 0.85

Calls 1

StringMethod · 0.80

Tested by 2

TestHexToBinaryFunction · 0.68
BenchmarkHexToBinaryFunction · 0.68