【问题标题】:Convert integer to binary string with variable size (C++)将整数转换为可变大小的二进制字符串(C++)
【发布时间】:2022-07-26 22:10:05
【问题描述】:

假设我想得到长度为n 的 1 和 0 的每个组合。比如n = 3,那么我想要

000
001
010
011
100
101
110
111

我最初的想法是使用类似的东西:

#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';
}

但这不起作用,因为std::bitset 需要一个常量,而我需要n 是可变的(例如,如果我处于循环中)。

我该怎么做?

【问题讨论】:

标签: c++


【解决方案1】:

一个简单的方法:使用按位移位操作提取每个位。

#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;
}

请注意,此方法仅在 n 小到不会导致整数溢出(1 &lt;&lt; n 不超过 INT_MAX)时才有效。
要生成更大的序列,可以使用递归:

#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;
}

【讨论】:

  • 请提及这项工作直到n = sizeof(int) - 2。
  • @paolo 你的意思是n = CHAR_BITS * sizeof(int) - 2?
  • 是的,你是对的。
猜你喜欢
  • 1970-01-01
  • 2012-08-16
  • 2012-02-27
  • 1970-01-01
  • 2018-03-01
  • 2018-07-07
  • 1970-01-01
  • 2016-10-04
相关资源
最近更新 更多