Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print an integer in binary with leading zeros?

Tags:

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?

like image 969
Neal Ehardt Avatar asked Jun 22 '17 04:06

Neal Ehardt


People also ask

What is a leading zero in binary?

A leading zero is any 0 digit that comes before the first nonzero digit in a number's binary form.

How do you print an int in binary?

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.

Can a binary number start with 0?

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.

How do you print the binary value of an integer in Python?

To print binary value of a given integer, we use bin() function it accepts the number as an argument and returns the binary value.


Video Answer


1 Answers

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 
like image 86
Neal Ehardt Avatar answered Sep 21 '22 08:09

Neal Ehardt