@@ -14,7 +14,6 @@ package conversion
1414import (
1515 "errors"
1616 "regexp"
17- "strconv"
1817 "strings"
1918)
2019
@@ -37,12 +36,43 @@ func hexToBinary(hex string) (string, error) {
3736 }
3837
3938 // 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
4353 }
4454
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
4878}
0 commit comments