在 C++11 中打印 std::bitset

Printing std::bitset in C++11

考虑以下用 C++11 编写的代码:

#include <iostream>
#include <bitset>
#include <cstdint>

int main() {

    std::uint64_t a = 0000000000000000000000000000000000000000000000001111111100000000;
    std::bitset<64> b(a);

    std::cout << b << std::endl;

    return 0;
}

代码的输出是:

0000000000000000001001001001001001001001000000000000000000000000

为什么这个输出与 a 值不对应?

如果你想写一个二进制数你需要使用0b前缀。

std::uint64_t a = 0b0000000000000000000000000000000000000000000000001111111100000000;
std::bitset<64> b(a);

Your example fixed and working live

如前所述,您的 "binary" 字符串实际上是一个更大数字的八进制表示。替代方法是从字符串、十进制表示形式或在字符串前加上“0b”前缀以表示后面是二进制表示形式

#include <iostream>
#include <bitset>
#include <cstdint>

int main() {

    std::bitset<64> foo (std::string("0000000000000000000000000000000000000000000000001111111100000000"));
    std::uint64_t  bar = foo.to_ulong();
    std::uint64_t beef = 0b0000000000000000000000000000000000000000000000001111111100000000;
    std::bitset<64> dead (beef);

    std::cout << foo << std::endl;
    std::cout << bar << std::endl;
    std::cout << dead << std::endl;
    std::cout << beef << std::endl;

    return 0;
}