|
| 1 | +/* |
| 2 | +Author: mapcrafter2048 |
| 3 | +GitHub: https://github.com/mapcrafter2048 |
| 4 | +*/ |
| 5 | + |
| 6 | +// This algorithm will convert any Hexadecimal number(0-9, A-F, a-f) to Binary number(0 or 1). |
| 7 | +// https://en.wikipedia.org/wiki/Hexadecimal |
| 8 | +// https://en.wikipedia.org/wiki/Binary_number |
| 9 | +// Function receives a Hexadecimal Number as string and returns the Binary number as string. |
| 10 | +// Supported Hexadecimal number range is 0 to 7FFFFFFFFFFFFFFF. |
| 11 | + |
| 12 | +package conversion |
| 13 | + |
| 14 | +import ( |
| 15 | + "errors" |
| 16 | + "regexp" |
| 17 | + "strings" |
| 18 | +) |
| 19 | + |
| 20 | +var isValidHex = regexp.MustCompile("^[0-9A-Fa-f]+$").MatchString |
| 21 | + |
| 22 | +// hexToBinary() function that will take Hexadecimal number as string, |
| 23 | +// and return its Binary equivalent as a string. |
| 24 | +func 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 | +} |
0 commit comments