hexhex/src/lib.rs

41 lines
896 B
Rust

fn print_printable_or_dot(chunk: &[u8]) {
for (idx, byte) in chunk.iter().enumerate() {
if idx > 0 && idx % 8 == 0 {
print!(" ");
}
if *byte >= 32 && *byte <= 126 {
print!("{}", String::from_utf8(vec![*byte]).unwrap());
} else {
print!(".");
}
}
}
fn print_offset(offset: usize) {
print!("{:08x} ", offset);
}
fn print_data_hex(chunk: &[u8]) {
for (idx, byte) in chunk.iter().enumerate() {
if idx > 0 && idx % 8 == 0 {
print!(" ");
}
print!("{:02x} ", byte);
}
}
pub fn print_hex(data: &[u8]) {
let mut offset = 0usize;
let chunks: Vec<&[u8]> = data.chunks(16).collect();
for chunk in chunks {
print_offset(offset);
print_data_hex(chunk);
print_printable_or_dot(chunk);
println!();
offset += 16;
}
}