Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary String to Integer with 'atoi()'

I have a string of binary that I then convert to an integer using atoi(). When I do this it seems to automatically convert the binary to decimal. The issue is that the resulting integer is negative and doesn't agree with any of the online binary-to-decimal converters. Is something broken with atoi()? Should I be using a different function instead?

Code:

string myString = "01000101";
int x = atoi(myString.c_str());
cout << x;

Thanks

like image 930
SkippyNBS Avatar asked May 11 '14 19:05

SkippyNBS


2 Answers

atoi doesn't handle binary numbers, it just interprets them as big decimal numbers. Your problem is that it's too high and you get an integer overflow due to it being interpreted as decimal number.

The solution would be to use stoi, stol or stoll that got added to string in C++11. Call them like

int i = std::stoi("01000101", nullptr, 2);
  • The returned value is the converted int value.
  • The first argument is the std::string you want to convert.
  • The second is a size_t * where it'll save the index of the first non digit character.
  • The third is an int that corresponds to the base that'll be used for conversion..

For information on the functions look at its cppreference page.


Note that there are also pre C++11 functions with nearly the same name, as example: strtol compared to the C++11 stol.
They do work for different bases too, but they don't do the error handling in the same way (they especially lack when no conversion could be done on the given string at all e.g trying to convert "hello" to a string) and you should probably prefer the C++11 versions.

To make my point, passing "Hello" to both strtol and the C++11 stol would lead to:

  • strtol returns 0 and doesn't give you any way to identify it as error,
  • stol from C++11 throws std::invalid_argument and indicates that something is wrong.

Falsely interpreting something like "Hello" as integers might lead to bugs and should be avoided in my opinion.

But for completeness sake a link to its cppreference page too.

like image 134
AliciaBytes Avatar answered Oct 02 '22 09:10

AliciaBytes


It sounds like you should be using strtol() with 2 as the last argument.

like image 29
NPE Avatar answered Oct 02 '22 11:10

NPE