Skip to content

Commit 5cd1c18

Browse files
authored
Add Binary to Hexadecimal Converter (#589)
1 parent 754aa20 commit 5cd1c18

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed
+102
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
// Author : cyrixninja
2+
// Binary to Hex Converter : Converts Binary to Hexadecimal
3+
// Wikipedia References : 1. https://en.wikipedia.org/wiki/Hexadecimal
4+
// 2. https://en.wikipedia.org/wiki/Binary_number
5+
6+
static BITS_TO_HEX: &[(u8, &str)] = &[
7+
(0b0000, "0"),
8+
(0b0001, "1"),
9+
(0b0010, "2"),
10+
(0b0011, "3"),
11+
(0b0100, "4"),
12+
(0b0101, "5"),
13+
(0b0110, "6"),
14+
(0b0111, "7"),
15+
(0b1000, "8"),
16+
(0b1001, "9"),
17+
(0b1010, "a"),
18+
(0b1011, "b"),
19+
(0b1100, "c"),
20+
(0b1101, "d"),
21+
(0b1110, "e"),
22+
(0b1111, "f"),
23+
];
24+
25+
fn bin_to_hexadecimal(binary_str: &str) -> String {
26+
let binary_str = binary_str.trim();
27+
28+
if binary_str.is_empty() {
29+
return String::from("Invalid Input");
30+
}
31+
32+
let is_negative = binary_str.starts_with('-');
33+
let binary_str = if is_negative {
34+
&binary_str[1..]
35+
} else {
36+
binary_str
37+
};
38+
39+
if !binary_str.chars().all(|c| c == '0' || c == '1') {
40+
return String::from("Invalid Input");
41+
}
42+
43+
let padded_len = (4 - (binary_str.len() % 4)) % 4;
44+
let binary_str = format!("{:0width$}", binary_str, width = binary_str.len() + padded_len);
45+
46+
// Convert binary to hexadecimal
47+
let mut hexadecimal = String::with_capacity(binary_str.len() / 4 + 2);
48+
hexadecimal.push_str("0x");
49+
50+
for chunk in binary_str.as_bytes().chunks(4) {
51+
let mut nibble = 0;
52+
for (i, &byte) in chunk.iter().enumerate() {
53+
nibble |= ((byte - b'0') as u8) << (3 - i);
54+
}
55+
56+
let hex_char = BITS_TO_HEX
57+
.iter()
58+
.find(|&&(bits, _)| bits == nibble)
59+
.map(|&(_, hex)| hex)
60+
.unwrap();
61+
hexadecimal.push_str(hex_char);
62+
}
63+
64+
if is_negative {
65+
format!("-{}", hexadecimal)
66+
} else {
67+
hexadecimal
68+
}
69+
}
70+
71+
#[cfg(test)]
72+
mod tests {
73+
use super::*;
74+
75+
#[test]
76+
fn test_empty_string() {
77+
let input = "";
78+
let expected = "Invalid Input";
79+
assert_eq!(bin_to_hexadecimal(input), expected);
80+
}
81+
82+
#[test]
83+
fn test_invalid_binary() {
84+
let input = "a";
85+
let expected = "Invalid Input";
86+
assert_eq!(bin_to_hexadecimal(input), expected);
87+
}
88+
89+
#[test]
90+
fn test_binary() {
91+
let input = "00110110";
92+
let expected = "0x36";
93+
assert_eq!(bin_to_hexadecimal(input), expected);
94+
}
95+
96+
#[test]
97+
fn test_padded_binary() {
98+
let input = " 1010 ";
99+
let expected = "0xa";
100+
assert_eq!(bin_to_hexadecimal(input), expected);
101+
}
102+
}

0 commit comments

Comments
 (0)