use std::fmt;
#[derive(Debug)] pub struct Number {
pub decimal: u32,
pub binary: String,
}
impl Number {
pub fn new(decimal_value: u32) -> Self {
Number {
decimal: decimal_value,
binary: Self::format_binary_with_separator(decimal_value),
}
}
fn format_binary_with_separator(n: u32) -> String {
let binary_string = format!("{:b}", n);
let len = binary_string.len();
let padded_len = match len {
0..=8 => 8,
9..=16 => 16,
17..=24 => 24,
_ => 32,
};
let padded_binary = format!("{:0>width$}", binary_string, width = padded_len);
let mut result = String::with_capacity(padded_len + (padded_len / 4) - 1);
for (i, c) in padded_binary.chars().enumerate() {
if i > 0 && i % 4 == 0 {
result.push('_');
}
result.push(c);
}
result
}
}
impl fmt::Display for Number {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "10진수로: {}, 2진수로: {}", self.decimal, self.binary)
}
}