3

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
m.qayyum
  • 409
  • 2
  • 9
  • 24

1 Answers1

11

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.

Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183