My initial intent was to convert a signed primitive number to its hexadecimal representation in a way that preserves the number\'s sign. It turns out that the current implem
This is like Francis Gagné's answer, but made generic to handle i8
through i128
.
use std::fmt::{self, Formatter, UpperHex};
use num_traits::Signed;
struct ReallySigned(T);
impl UpperHex for ReallySigned {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let prefix = if f.alternate() { "0x" } else { "" };
let bare_hex = format!("{:X}", self.0.abs());
f.pad_integral(self.0 >= T::zero(), prefix, &bare_hex)
}
}
fn main() {
println!("{:#X}", -0x12345678);
println!("{:#X}", ReallySigned(-0x12345678));
}