Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Literals in C++

Can I add binary literal prefix in c++ before a user input int value.

#include <iostream>
using namespace std;

int main () {
 int n1;
 cin>>n1;
 string s1 = to_string(n1); 
  string s2 = "0b";
string s=s2+s1;
int n=stoi(s);
cout<<n;
return 0;
}

I tried this but failed as stoi() only reads 0 and skips the rest

like image 532
Shaurya Singh Avatar asked Jun 06 '26 09:06

Shaurya Singh


1 Answers

There's still no way of reading a binary number directly from standard input. Any auto-detection of the radix does not support "0b", so stoi() stops when 'b' is reached.

If s is a std::string read from standard input (std::cin >> s; perhaps), without the "0b" prefix, then you can use

#include <cstdlib>
char* end;
long n = std::strtol(s.c_str(), &end, 2/*radix of 2 denotes binary*/);

checking the pointer end in case there are invalid binary digits in s.

Note that I'm using strtol rather than stoi as an int can have a upper limits as small as 32767.

like image 58
Bathsheba Avatar answered Jun 07 '26 22:06

Bathsheba