0

Consider the following code written in 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;
}

The output of the code is :

0000000000000000001001001001001001001001000000000000000000000000

Why this output does not correspond to the a value?

Romain
  • 1,385
  • 2
  • 15
  • 30

2 Answers2

10

If you want to write a binary number you need to use the 0b prefix.

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

Your example fixed and working live

R Sahu
  • 204,454
  • 14
  • 159
  • 270
Hiura
  • 3,500
  • 2
  • 20
  • 39
3

As mentioned your "binary" string is actually an octal representation of a much larger number. Alternative methods would be converting from a string, from the decimal representation or prefixing the string with '0b' to denote that a binary representation follows

#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;
}
bitspill
  • 131
  • 7