-3

How can I generate all possible binary numbers like below:

0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111


List<int> GetAllPossibleBinaryNumbers(int length) {
}

In above GetAllPossibleBinaryNumbers accepts length as the number of bits, and returns all possible binary values.

Imran Qadir Baksh - Baloch
  • 32,612
  • 68
  • 179
  • 322
  • I mean look through all possible binary numbers – Imran Qadir Baksh - Baloch May 29 '21 at 20:17
  • 1
    @user960567 Please show your attempts you have tried and the problems/error messages you get from your attempts. – Progman May 29 '21 at 20:21
  • 1
    Yes I wanna all possible binary numbers of length n – Imran Qadir Baksh - Baloch May 29 '21 at 20:24
  • Does this answer your question? [Generate all binary strings of length n with k bits set](https://stackoverflow.com/questions/1851134/generate-all-binary-strings-of-length-n-with-k-bits-set) –  May 29 '21 at 20:25
  • https://www.geeksforgeeks.org/generate-all-the-binary-strings-of-n-bits/ –  May 29 '21 at 20:26
  • I’m voting to close this question because the user wants to count, but has shown no effort. – HABO May 29 '21 at 20:32
  • The duplicate you cited generates values with _k_ bits set, not _all_ possible combinations. In any event, the [Help Vampire](https://web.archive.org/web/20180216144029/https://www.skidmore.edu/~pdwyer/e/eoc/help_vampire.htm) has posted a problem statement that shows _zero_ bits set for effort. They couldn't even be bothered to suggest that the values shown were for `length = 4`. – HABO May 29 '21 at 20:40
  • @OlivierRogier There is only _one_ value for `k = length`: all bits set. – HABO May 29 '21 at 20:44

1 Answers1

2

Calculate how many numbers there are (which is 2^n), start a loop at 0 and end at 2^n - 1.

int length = 4;
int numbers = 1 << length; // equivalent of 2^n
for(int i=0; i<numbers; i++)
{
    string binary = Convert.ToString(i, 2);
    string leading_zeroes = "00000000".Substring(0,length-binary.Length);
    Console.WriteLine(leading_zeroes + binary);
}
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222