Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created July 3, 2020 20:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rust-play/3dc108caa32dc8533a5e1e5972951ab1 to your computer and use it in GitHub Desktop.
Save rust-play/3dc108caa32dc8533a5e1e5972951ab1 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::fmt;
fn main() -> Result<(), &'static str> {
let b = vec![0x64, 0x61, 0x76, 0x65];
println!("{}", b.to_hex());
Ok(())
}
trait ToHex {
fn to_hex(&self) -> String;
}
impl<T: fmt::LowerHex> ToHex for T {
fn to_hex(&self) -> String {
format!("{:x}", self)
}
}
impl ToHex for [u8] {
fn to_hex(&self) -> String {
use core::fmt::Write;
let mut ret = String::with_capacity(2 * self.len());
for ch in self {
write!(ret, "{:02X}", ch).expect("writing to string");
}
ret
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment