Skip to content

Instantly share code, notes, and snippets.

@goldsborough
Created March 9, 2018 08:50
Show Gist options
  • Save goldsborough/a7d0d20807d9428f4e8f66e15f16b077 to your computer and use it in GitHub Desktop.
Save goldsborough/a7d0d20807d9428f4e8f66e15f16b077 to your computer and use it in GitHub Desktop.
hex parser in rust
macro_rules! hex {
(0) => {48};
(9) => {57};
(A) => {65};
(F) => {70};
(a) => {97};
(z) => {102};
(0..9) => {48...57};
(A..F) => {65...70};
(a..f) => {97...102};
}
pub fn parse_hex_address(string: &str) -> Option<usize> {
debug_assert!(!string.starts_with("0x"));
let mut value: usize = 0;
let mut base: usize = 1;
for byte in string.bytes().rev() {
let digit = match byte {
hex!(0..9) => byte - hex!(0),
hex!(A..F) => 10 + (byte - hex!(A)),
hex!(a..f) => 10 + (byte - hex!(a)),
_ => return None,
};
value += base * (digit as usize);
base *= 16;
}
Some(value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment