0

Is there a way to convert a decimal to a 16-bit binary in Rust using the standard library?

I have this sample:

let x: u16 = 21;
println!("{}",format!("{:b}", x)); // output: 10101

but I need it to include the leading zeroes. like: 21 to 0000000000010101

I could create a function to add the leading zeroes but I was wondering if I'm missing something in its standard library.

Here are the methods from the std on u16 primitive type: https://doc.rust-lang.org/stable/std/primitive.u16.html

halfer
  • 19,824
  • 17
  • 99
  • 186
aRtoo
  • 1,686
  • 2
  • 18
  • 38
  • 1
    Does this answer your question? [What is the easiest way to pad a string with 0 to the left?](https://stackoverflow.com/questions/50458144/what-is-the-easiest-way-to-pad-a-string-with-0-to-the-left) Particularly the second answer is almost directly what you want, except 16 instead of 8 – kmdreko Sep 12 '21 at 02:56
  • 1
    Check: https://doc.rust-lang.org/stable/std/fmt/index.html - `{:016b}` should do it. – harmic Sep 12 '21 at 02:57

0 Answers0