@@ -14,7 +14,6 @@ package conversion
14
14
import (
15
15
"errors"
16
16
"regexp"
17
- "strconv"
18
17
"strings"
19
18
)
20
19
@@ -37,12 +36,43 @@ func hexToBinary(hex string) (string, error) {
37
36
}
38
37
39
38
// Parse the hexadecimal string to an integer
40
- decimal , err := strconv .ParseInt (hex , 16 , 64 )
41
- if err != nil {
42
- return "" , errors .New ("failed to parse hexadecimal string " + hex + ": " + err .Error ())
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
43
53
}
44
54
45
- // Convert the integer to a binary string
46
- binary := strconv .FormatInt (decimal , 2 )
47
- return binary , nil
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
48
78
}
0 commit comments