How to read a binary number as input?

前端 未结 4 1828
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 12:35

Is there a way for the user to input a binary number in C or C++?

If we write something like

int a = 0b1010;
std::cout << a << std::endl
         


        
4条回答
  •  庸人自扰
    2021-02-03 13:23

    There is a bit of confusion here, let's disentangle it a bit.

    • 0b1010 is an integer literal, a constant, compile-time integer value written in base 2. Likewise, 0xA is a literal in base 16 and 10 is in base 10. All of these refer to the same integer, it is just a different way of telling the compiler which number you mean. At runtime, in memory, this integer is always represented as a base-2 number.

    • std::cout << a; takes the integer value of a and outputs a string representation of it. By default it outputs it in base 10, but you can i.e use the std::hex modifier to have it output it in base 16. There is no predefined modifier to print in binary. So you need to do that on your own (or google it, it is a common question).

    • 0b at last, is only used to define integer literals. It is not a runtime operator. Recall, all ints are represented as base 2 numbers in memory. Other bases do not exist from a machine point of view, int is int, so there is nothing to convert. If you need to read a binary number from a string, you would roll the reverse code to what you do to print it (std::cin >> n assumes that the input is a base 10 number, so it reads a wrong number if the input is actually intended to be in base 2).

提交回复
热议问题