Skip to content

Instantly share code, notes, and snippets.

@pshc
Last active December 16, 2015 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pshc/5427000 to your computer and use it in GitHub Desktop.
Save pshc/5427000 to your computer and use it in GitHub Desktop.
fn hex_to_bytes(hex: &str) -> ~[u8] {
let n = hex.len();
assert!(n % 2 == 0);
return vec::from_fn(n / 2, |i| {
u8::from_str_radix(hex.substr(i*2, 2), 16).expect("bad hex")
});
}
fn bytes_to_hex(bytes: &[u8]) -> ~str {
let hex_chars = ~"0123456789abcdef";
let n = bytes.len();
let mut hex = str::with_capacity(n * 2);
do bytes.each |byte| {
hex.push_char(hex_chars[*byte >> 4] as char);
hex.push_char(hex_chars[*byte & 0xf] as char);
true
};
return hex;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment