Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an integer to a binary string with leading zeros

Tags:

c#

binary

I need to convert int to bin and with extra bits.

string aaa = Convert.ToString(3, 2); 

it returns 11, but I need 0011, or 00000011.

How is it done?

like image 374
arturas Avatar asked May 28 '14 07:05

arturas


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 convert integer to binary representation?

To convert integer to binary, start with the integer in question and divide it by 2 keeping notice of the quotient and the remainder. Continue dividing the quotient by 2 until you get a quotient of zero. Then just write out the remainders in the reverse order.

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.


1 Answers

11 is binary representation of 3. The binary representation of this value is 2 bits.

3 = 20 * 1 + 21 * 1

You can use String.PadLeft(Int, Char) method to add these zeros.

// convert number 3 to binary string.  // And pad '0' to the left until string will be not less then 4 characters Convert.ToString(3, 2).PadLeft(4, '0') // 0011 Convert.ToString(3, 2).PadLeft(8, '0') // 00000011 
like image 73
Soner Gönül Avatar answered Sep 28 '22 03:09

Soner Gönül