Wednesday 13 May 2015

Rust: byte array to hex String

This code allows you to express arbitrary octet sequences as hex.

pub fn to_hex_string(bytes: Vec<u8>) -> String {
  let strs: Vec<String> = bytes.iter()
                               .map(|b| format!("{:02X}", b))
                               .collect();
  strs.connect(" ")
}

#[cfg(test)]
mod test {
  use super::*;

  #[test]
  fn test_to_hex_string() {
    let bytes: Vec<u8> = vec![0xFF, 0, 0xAA];
    let actual = to_hex_string(bytes);
    assert_eq!("FF 00 AA", actual);
  }
}

This function turns a byte vector into a space-delimited hex string using an iterator to map the values.

This post is just a code snippet written by someone getting started. No promises are made about code quality. Version: rustc 1.0.0-beta.4 (850151a75 2015-04-30) (built 2015-04-30)

No comments:

Post a Comment

All comments are moderated