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
?
A leading zero is any 0 digit that comes before the first nonzero digit in a number's binary form.
To print binary representation of unsigned integer, start from 31th bit, check whether 31th bit is ON or OFF, if it is ON print “1” else print “0”. Now check whether 30th bit is ON or OFF, if it is ON print “1” else print “0”, do this for all bits from 31 to 0, finally we will get binary representation of number.
In every binary number, the first digit starting from the right side can equal 0 or 1. But if the second digit is 1, then it represents the number 2. If it is 0, then it is just 0.
To print binary value of a given integer, we use bin() function it accepts the number as an argument and returns the binary value.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With