m.qayyum m.qayyum - 2 months ago 5
Vb.net Question

How to convert a decimal number to a binary number with fixed bits

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.

Answer

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.

Comments