0

I found some answers on converting decimal to binary and I made this code and its working fine,

int number = 2;
string binary = Convert.ToString(number, 2); // gives 10 as binary

But what I want is 00010 as five digit no.

And I am not looking to convert into HEX,

How do I get that?

  • 1
    How about `String.PadLeft`. – Nikhil Agrawal Jan 23 '18 at 09:54
  • 1
    It might be a duplicate but not of [the current duplicate](https://stackoverflow.com/questions/4416974/convert-10-digit-number-to-hex-string) selected. I didn't find any standard numeric format string that converts the number to it's binary representation. – Zohar Peled Jan 23 '18 at 14:20

2 Answers2

4

Use PadLeft:

var binary = Convert.ToString(number, 2).PadLeft(5, '0');

See a live demo on rextester.

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
1

fast solution :

int number = 2;
string binary = Convert.ToString(number, 2); // gives 10 as binary
if (binary.Length < 5) binary = new String('0',5- binary.Length ) + binary;

output : 00010

Mohamed Sa'ed
  • 781
  • 4
  • 13