Skip to content

Instantly share code, notes, and snippets.

@ellygaytor
Created April 11, 2022 17:31
Show Gist options
  • Save ellygaytor/1d91a0c0de95843157ddde523ad2079d to your computer and use it in GitHub Desktop.
Save ellygaytor/1d91a0c0de95843157ddde523ad2079d to your computer and use it in GitHub Desktop.
Simple rust library to convert a string containing hexadecimal data to base 10 numbers. Not on crates.io.
/// Convert a single hex character to its integer value. `Err` if the character is not a hex character.
fn convert_digit(digit: &str) -> Option<u8>{
match digit {
"0" => Some(0),
"1" => Some(1),
"2" => Some(2),
"3" => Some(3),
"4" => Some(4),
"5" => Some(5),
"6" => Some(6),
"7" => Some(7),
"8" => Some(8),
"9" => Some(9),
"A" | "a" => Some(10),
"B" | "b" => Some(11),
"C" | "c" => Some(12),
"D" | "d" => Some(13),
"E" | "e" => Some(14),
"F" | "f" => Some(15),
_ => None,
}
}
/// Convert a hex string to a u32 value.
/// Expects a string containing only hex digits, upper or lower case, with an optional 0x prefix.
/// Returns Err if the string is not a valid hex string.
pub fn hex_to_decimal(hex: &str) -> Result<u32, &'static str> {
if hex.is_empty() {
return Err("Empty string");
}
let mut hex = hex;
if hex.starts_with("0x") {
hex = &hex[2..];
}
let mut result: u32 = 0;
let mut hex_iter = hex.chars();
let mut hex_digit = hex_iter.next();
while hex_digit.is_some() {
let digit = convert_digit(hex_digit.unwrap().to_string().as_str());
if digit.is_none() {
return Err("Invalid hex digit");
}
result = result * 16 + digit.unwrap() as u32;
hex_digit = hex_iter.next();
}
Ok(result)
}
#[cfg(test)]
mod tests {
#[test]
fn test_c2() {
assert_eq!(200, hex_to_decimal("C8").unwrap());
}
#[test]
fn test_empty_string() {
assert_eq!(Err("Empty string"), hex_to_decimal(""));
}
#[test]
fn test_invalid_hex_digit() {
assert_eq!(Err("Invalid hex digit"), hex_to_decimal("G"));
}
#[test]
fn test_ffffff() {
assert_eq!(16777215, hex_to_decimal("FFFFFF").unwrap());
}
#[test]
fn test_0xffffff() {
assert_eq!(16777215, hex_to_decimal("0xFFFFFF").unwrap());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment