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?
A leading zero is any 0 digit that comes before the first nonzero digit in a number's binary form.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With