-1

That might be a easy problem but I'm still stacked on it.

I have string variable number = 11111111111111111111111111111110 and in decimal is 4294967294.

I couldn't use atoi because its value bypass int value. I tried also istringstream and strtoul and both of them gave inaccurate results.

What am I missing here?

Jongware
  • 22,200
  • 8
  • 54
  • 100
user3764893
  • 697
  • 5
  • 16
  • 33
  • 8
    4294967294 does fit into an unsigned 32-bit integer, just. But it looks like you're trying to parse your string as a decimal number -- it seems to be in binary instead. Make sure you pass a radix (the number's base) of 2. – Cameron Feb 18 '15 at 15:00
  • http://stackoverflow.com/questions/117844/converting-string-of-1s-and-0s-into-binary-value – Jepessen Feb 18 '15 at 15:00
  • What you are missing? first of all show your code. – Doro Feb 18 '15 at 15:01
  • `strtoul` should work if used correctly. – interjay Feb 18 '15 at 15:03
  • Or `strtoull` if you need to cater to larger numbers. – Klas Lindbäck Feb 18 '15 at 15:05
  • You could also just go about and assemble the number yourself. Most of the difficulties will arise from error checking (overly long string, int overflow, bad chars, empty string), so if you can be sure about your input it's not difficult to add up powers of 2. In fact, what you see *is* a bit pattern! (In production code, of course, library functions are almost always preferable by far.) – Peter - Reinstate Monica Feb 18 '15 at 15:06

1 Answers1

1

strtoul accepts a third parameter that define the base. set the base to 2

unsigned long parsedValue;
std::string binaryNumber("11111111111111111111111111111110");
parsedValue= strtoul(binaryNumber.c_str(), NULL, 2);

http://www.cplusplus.com/reference/cstdlib/strtoul/?kw=strtoul

Jepessen
  • 11,744
  • 14
  • 82
  • 149