【问题标题】:Printing std::bitset in C++11 [closed]在 C++11 中打印 std::bitset [关闭]
【发布时间】:2015-04-25 04:42:51
【问题描述】:

考虑以下用 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 值不对应?

【问题讨论】:

标签: c++ c++11 bitset uint64


【解决方案1】:

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

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

Your example fixed and working live

【讨论】:

    【解决方案2】:

    如前所述,您的“二进制”字符串实际上是一个更大数字的八进制表示。替代方法是从字符串转换,从十进制表示或在字符串前面加上“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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      • 2014-10-02
      • 2011-07-30
      • 2013-12-07
      • 1970-01-01
      • 1970-01-01
      • 2013-02-16
      相关资源
      最近更新 更多