用法
pub trait Binary {
fn fmt(&self, f:&mut Formatter<'_>) -> Result<(), Error>;
}
b
格式化。
Binary
特征应将其输出格式化为二进制数字。
对于原始有符号整数( i8
到 i128
和 isize
),负值被格式化为二进制补码表示。
备用标志 #
在输出前添加 0b
。
有关格式化程序的更多信息,请参阅module-level 文档。
例子
i32
的基本用法:
let x = 42; // 42 is '101010' in binary
assert_eq!(format!("{:b}", x), "101010");
assert_eq!(format!("{:#b}", x), "0b101010");
assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
在类型上实现Binary
:
use std::fmt;
struct Length(i32);
impl fmt::Binary for Length {
fn fmt(&self, f:&mut fmt::Formatter<'_>) -> fmt::Result {
let val = self.0;
fmt::Binary::fmt(&val, f) // delegate to i32's implementation
}
}
let l = Length(107);
assert_eq!(format!("l as binary is:{:b}", l), "l as binary is:1101011");
assert_eq!(
format!("l as binary is:{:#032b}", l),
"l as binary is:0b000000000000000000000001101011"
);
相关用法
- Rust alloc::fmt::Result用法及代码示例
- Rust alloc::fmt::DebugStruct.finish用法及代码示例
- Rust alloc::fmt::Formatter.fill用法及代码示例
- Rust alloc::fmt::Formatter.sign_plus用法及代码示例
- Rust alloc::fmt::Arguments用法及代码示例
- Rust alloc::fmt::Formatter.debug_set用法及代码示例
- Rust alloc::fmt::DebugTuple.field用法及代码示例
- Rust alloc::fmt::Error用法及代码示例
- Rust alloc::fmt::DebugStruct用法及代码示例
- Rust alloc::fmt::Formatter.sign_aware_zero_pad用法及代码示例
- Rust alloc::fmt::DebugStruct.field用法及代码示例
- Rust alloc::fmt::Formatter.width用法及代码示例
- Rust alloc::fmt::DebugSet.entry用法及代码示例
- Rust alloc::fmt::Formatter.pad用法及代码示例
- Rust alloc::fmt::DebugMap用法及代码示例
- Rust alloc::fmt::Write.write_fmt用法及代码示例
- Rust alloc::fmt::DebugStruct.finish_non_exhaustive用法及代码示例
- Rust alloc::fmt::DebugMap.entry用法及代码示例
- Rust alloc::fmt::LowerExp用法及代码示例
- Rust alloc::fmt::Formatter.align用法及代码示例
注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 Trait alloc::fmt::Binary。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。