How to read binary number as input?

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

If we write something like

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

Then the output will be 10 (using the appropriate compiler extensions).

but when we try to write

 int n; std::cin >> n; int t = 0bn; 

This gives us an error, so can anyone suggest that we can directly read the binary as input, rather than use a string to store the input?

+6
source share
3 answers

There is a little confusion, let it go a little.

  • 0b1010 is an integer literal, a constant integer value of compilation time, written in base 2. Similarly, 0xA is a literal in base 16 and 10 is in base 10. They all refer to the same integer , this is just another way to tell the compiler which the number you mean. At run time in memory, this integer is always represented as base number 2.

  • std::cout << a ; takes an integer value of a and displays its string representation. By default, it outputs it to base 10, but you can use the std::hex modifier to output it to base 16. There is no predefined modifier for printing in binary format . So you need to do it yourself (or google, this is a general question).

  • 0b finally only used to define integer literals. This is not a runtime statement. Recall that all int 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 flip the reverse code to what you do to print it ( std::cin >> n assumes that the input is base number 10, so it reads the wrong number if the input itself intended for base 2).

+5
source

While there is no function for directly reading binary numbers, there are strtox functions (where x represents the data type) to convert a string containing a binary number (or the number of any other base) to a numeric value.

So, the solution is to read the number as a string first and then convert it.

Example:

 char input[100]; char *endpointer; <read input using either C or C++ syntax> int n = (int) strtol(input, &endpointer, 2); 
+7
source

do it yourself soon:

 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); 
+1
source

Source: https://habr.com/ru/post/974195/


All Articles