40

I'm doing some bit twiddling and I'd like to print all the bits in my u16.

let flags = 0b0000000000101100u16;
println!("flags: {:#b}", flags);

This prints flags: 0b101100.

How do I make it print flags: 0b0000000000101100?

Neal Ehardt
  • 10,334
  • 9
  • 41
  • 51

2 Answers2

72
let flags = 0b0000000000101100u16;
println!("flags: {:#018b}", flags);

The 018 pads with zeros to a width of 18. That width includes 0b (length=2) plus a u16 (length=16) so 18 = 2 + 16. It must come between # and b.

Rust's fmt docs explain both leading zeros and radix formatting, but don't show how to combine them.

Here are u8, u16, and u32:

//                       Width  0       8      16      24      32
//                              |       |       |       |       |
println!("{:#010b}", 1i8);  // 0b00000001
println!("{:#018b}", 1i16); // 0b0000000000000001
println!("{:#034b}", 1i32); // 0b00000000000000000000000000000001
Neal Ehardt
  • 10,334
  • 9
  • 41
  • 51
  • 1
    How can I put underscores in between to make it more readable? – Atul Gopinathan Dec 30 '20 at 04:30
  • 1
    @AtulGopinathan you will need a custom crate. https://stackoverflow.com/questions/26998485/is-it-possible-to-print-a-number-formatted-with-thousand-separator-in-rust – Neal Ehardt Jan 06 '21 at 20:47
  • 16
    How about using `0b{:08b}` instead of `{:#010b}`? It's easier to reason `8` than `10`. – kbridge4096 Jan 28 '22 at 18:32
  • 2
    @AtulGopinathan A crate for this is convenient, but not necessary; instead of `println!("{:08b}", my_u8_value)`, try `println!("{:04b}_{:04b}", my_u8_value >> 4, my_u8_value & 0x0f)` – U007D Oct 20 '22 at 12:45
2

I have come to prefer these patterns:

println!("{:08b}", 1i8);
println!("{:016b}", 12000u16);
println!("{:032b}", 624485u32);

it will print:

00000001
0010111011100000
00000000000010011000011101100101
Jonas
  • 121,568
  • 97
  • 310
  • 388