How to read a binary number as input?

前端 未结 4 1825
爱一瞬间的悲伤
爱一瞬间的悲伤 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:07

    rather do it yourself:

    uint32_t a = 0;
    
    char c;
    while ((c = getchar()) != '\n') { // read a line char by char
      a <<= 1;                        // shift the uint32 a bit left
      a += (c - '0') & 1;             // convert the char to 0/1 and put it at the end of the binary
    }
    
    printf("%u\n", a);
    

提交回复
热议问题