Can I use a binary literal in C or C++?

前端 未结 19 2647
梦如初夏
梦如初夏 2020-11-22 07:40

I need to work with a binary number.

I tried writing:

const x = 00010000;

But it didn\'t work.

I know that I can use an hex

19条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 08:10

    Just use the standard library in C++:

    #include 
    

    You need a variable of type std::bitset:

    std::bitset<8ul> x;
    x = std::bitset<8>(10);
    for (int i = x.size() - 1; i >= 0; i--) {
          std::cout << x[i];
    }
    

    In this example, I stored the binary form of 10 in x.

    8ul defines the size of your bits, so 7ul means seven bits and so on.

提交回复
热议问题