How to convert a decimal number to a binary number with fixed bits
23,858
This code should do what you're looking for:
For i As Integer = 0 To 15
Console.WriteLine(Convert.ToString(i, 2).PadLeft(4, "0"C))
Next
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
The "2" in Convert.ToString(i, 2)
means binary. PadLeft(4, "0"C)
means that if the string isn't four characters, append zeros to the beginning until it is four characters.
Author by
m.qayyum
Updated on July 28, 2022Comments
-
m.qayyum almost 2 years
I want to convert numbers from 0 to 15 like this:
0000 0001 0010 0011 . . . 1111
The problem is that when we convert 2 to a binary number it gives only 10 in binary, but I want to convert 2 to 4-bit binary number 0010.
-
m.qayyum over 13 yearsFor i As Integer = 0 To 15 Console.WriteLine(Convert.ToString(i, 2).PadLeft(4, "0"c)) Next i
-
Merlyn Morgan-Graham over 13 years@m.qayyum: Thanks. I found an online converter. Glad it gave the right output ;)
-
m.qayyum over 13 yearsYa i also used c to vb converter ;)