Once again, I am reinventing the wheel here to understand the fundamentals of rust. In a previous question I requested feedback on my function that performed a hexadecimal to binary conversion. In this snippet, I am seeking some constructive feedback on converting from binary to hexadecimal.
fn main() {
let hexadecimal_value = convert_to_hex_from_binary("10111");
println!("Converted: {}", hexadecimal_value);
}
fn convert_to_hex_from_binary(binary: &str) -> String {
let padding_count = 4 - binary.len() % 4;
let padded_binary = if padding_count > 0 {
["0".repeat(padding_count), binary.to_string()].concat()
} else {
binary.to_string()
};
let mut counter = 0;
let mut hex_string = String::new();
while counter < padded_binary.len() {
let converted = to_hex(&padded_binary[counter..counter + 4]);
hex_string.push_str(converted);
counter += 4;
}
hex_string
}
fn to_hex(b: &str) -> &str {
match b {
"0000" => "0",
"0001" => "1",
"0010" => "2",
"0011" => "3",
"0100" => "4",
"0101" => "5",
"0110" => "6",
"0111" => "7",
"1000" => "8",
"1001" => "9",
"1010" => "A",
"1011" => "B",
"1100" => "C",
"1101" => "D",
"1110" => "E",
"1111" => "F",
_ => "",
}
}