Home > Mobile >  Convert integer to binary string with variable size (C )
Convert integer to binary string with variable size (C )

Time:07-27

Suppose I want to get every combination of 1's and 0's with length n. For example, if n = 3, then I want

000
001
010
011
100
101
110
111

My initial thought was to use something like:

#include <iostream>
#include <bitset>
#include <cmath>

int main() {
  int n = 3;
  for (int i = 0; i < pow(2, n); i  )
    std::cout << std::bitset<n>(i).to_string() << '\n';
}

but this does not work since std::bitset takes a const, whereas I need n to be variable (for example if I am in a loop).

How can I do this?

CodePudding user response:

A straightforward way: Extract each bits using bitwise shift operation.

#include <iostream>

int main() {
    int n = 3;
    for (int i = 0; i < (1 << n); i  ) {
        for (int j = n - 1; j >= 0; j--) {
            std::cout << ((i >> j) & 1);
        }
        std::cout << '\n';
    }
    return 0;
}

Note that this method will work only if n is small enough not to cause an integer overflow (1 << n doesn't exceed INT_MAX).
To generate larger sequence, you can use recursion:

#include <iostream>
#include <string>

void printBits(int leftBits, const std::string& currentBits) {
    if (leftBits <= 0) {
        std::cout << currentBits << '\n';
    } else {
        printBits(leftBits - 1, currentBits   "0");
        printBits(leftBits - 1, currentBits   "1");
    }
}

int main() {
    int n = 3;
    printBits(n, "");
    return 0;
}

CodePudding user response:

C 20 format to the rescue:

int main()
{
    int p;
    while (std::cin >> p) {
        std::cout << std::format("--------\n2^{}\n", p);
        auto n = 1 << p;
        
        for (int i = 0; i < n; i  ) {
            std::cout << std::format("{:0{}b}\n", i, p);
        }
    }
}

https://godbolt.org/z/5so59GGMq

Sadly for now only MSVC supports it.

  •  Tags:  
  • c
  • Related