考虑以下用 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);
您的示例已修复并实时工作
如前所述,您的"二进制"字符串实际上是更大数字的八进制表示。替代方法是从字符串、十进制表示形式转换或在字符串前面加上"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;
}