add binary display

This commit is contained in:
numzero 2025-11-02 02:08:06 +03:00
parent ea40afef2d
commit fc87672e10

View File

@ -40,6 +40,21 @@ impl F8 {
}
}
impl std::fmt::Binary for F8 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if f.alternate() {
f.write_str("0b")?;
}
if self.0 == 0 {
f.write_str("0.00000p0")?;
return Ok(());
}
let (m, e) = self.split();
write!(f, "1.{m:05b}p{e}", e = e as i8 - E_BIAS as i8)?;
Ok(())
}
}
impl From<u8> for F8 {
fn from(v: u8) -> Self {
if v == 0 {
@ -112,4 +127,18 @@ mod tests {
assert_eq!(f32::from(F8::from(k)), k as f32);
}
}
#[test]
fn test_display() {
fn fmt_split(m: u8, e: u8) -> String {
let v = F8::merge(m, e);
format!("{v:b}")
}
assert_eq!("0.00000p0", fmt_split(0, 0));
assert_eq!("1.00000p0", fmt_split(0, E_BIAS));
assert_eq!("1.00000p1", fmt_split(0, E_BIAS + 1));
assert_eq!("1.00000p-1", fmt_split(0, E_BIAS - 1));
assert_eq!("1.00001p0", fmt_split(1, E_BIAS));
assert_eq!("1.11111p0", fmt_split(0b11111, E_BIAS));
}
}