How to read a binary number as input?
Asked Answered
B

4

12

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

Then the output comes out to be 10 (when using the appropriate compiler extensions).

but when we try to write

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

It gives us an error so can anyone suggest that how can we directly read binary number as input rather than using string to store input?

Bifacial answered 22/8, 2014 at 7:5 Comment(2)
google search, first entry: cplusplus.com/forum/general/103479Jariah
@Jariah That's what I think the question is actually about. It's too bad they don't have a bin IO manipulator to go with hex and dec and oct. Maybe I'll try to propose one now that binary literals are a standard thing.Browning
U
10

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).

Urban answered 22/8, 2014 at 7:23 Comment(4)
I'd suggest removing the "At runtime, in memory, this integer is always represented as a base-2 number." bit. It's unnecessarily wrong. At runtime the number is just a number. (Not at runtime it's still just a number as well.) You can't see the representation used by the program unless you do shady tricks, and knowing the representation it's mostly useless anyway. It doesn't have to be base-2 and it actually isn't in practice, not for any mainstream compiler (two's complement is not even a radix number system, so how can it be base-2?).How
I included it given OP wants to print it in binary, for which most recommendations will be to use bitwise operations to extract the bits. Which of course, doesn't strictly mean it is stored in base-2, but strongly suggests it.Urban
@R.Martinho: Interesting quibble about 2's complement not being a pure radix system. It is still binary though, with base-2 place values except for the sign bit. (I think "binary" is a better term for the run-time representation anyway).Fils
(And BTW, ISO C and C++ do require that unsigned integer types are actually base 2, with bits in normal place-value order: they wrap at modulo 2^n for some n where n is the number of bits in the value representation of that particular size of integer (N4140 section 3.9.1 Fundamental types, item 4). And unsigned char has no padding: all object bits are value representation bits. (And you can cast to char* to look at the representation of anything). Trinary hardware would have to emulate... The bits-in-order req comes from the description of shifts as actually shifting bits, not *2Fils
L
9

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

So the solution is to first read the number as a string 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);
Lightsome answered 22/8, 2014 at 7:28 Comment(0)
I
6

To take a binary number as input, there are two ways I use frequently:

(Keynote: Take the input as string!!! use: #include <string>)

  1. The to_ulong() method of the bitset template of the bitset library
    • for this you need to include the bitset library using #include <bitset>

Example:

string s;
cin>>s; // Suppose s = "100100101"
int n = (int) bitset<64>(s).to_ulong();
cout<<n; // 293

Explore more about bitset here and about to_ulong() here.

  1. The stoi() method of the string library
    • for this you need to include the string library using #include <string>

Example:

string s;
cin>>s; // Suppose s = "100100101"
int n = stoi(s, 0, 2);
cout<<n; // 293

Explore the format of stoi() here.

Impede answered 2/11, 2019 at 18:18 Comment(0)
S
1

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);
Secularism answered 24/10, 2016 at 16:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.