Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pad a binary string with zeros?

string binary = Convert.ToString(15, 2);

Console.WriteLine("{0}", binary);

Prints:

1111

I want it to print 00001000

Because the data type is of string and not integer I cannot do something like this:

Console.WriteLine("{0:00000000}", binary);
like image 520
Ryan Peschel Avatar asked Oct 07 '11 02:10

Ryan Peschel


People also ask

How to pad a numeric value with a specific number of zeros?

To pad a numeric value with a specific number of leading zeros. Create a custom format string that uses the zero placeholder ("0") for each of the leading zeros to appear in the string, and that uses either the zero placeholder or the digit placeholder ("#") to represent each digit in the default string.

How do you pad a number with leading zeros in Python?

To pad a numeric value with leading zeros to a specific length Determine how many digits to the left of the decimal you want the string representation of the number to have. Include any leading zeros in this total number of digits. Define a custom numeric format string that uses the zero placeholder "0" to represent the minimum number of zeros.

How to pad string with zeros in Java 5?

And, finally, since Java 5, we can use String.format (): We should note that by default the padding operation will be performed using spaces. That's the reason why we need to use the replace () method if we want to pad with zeros or any other character.

How to pad an integer with leading zeros to a specific length?

To pad an integer with leading zeros to a specific length. To display the integer as a hexadecimal value, call its ToString (String) method and pass the string "X n " as the value of the format parameter, where n represents the minimum length of the string.


2 Answers

Console.WriteLine( binary.PadLeft(8, '0'));
like image 109
Bala R Avatar answered Oct 20 '22 04:10

Bala R


You can try this one:

Convert.ToString(15, 2).PadLeft(8, '0');

It should give you 00001111

like image 38
Bryan Hong Avatar answered Oct 20 '22 02:10

Bryan Hong