Binary String to Integer with 'atoi()'

后端 未结 2 1349
栀梦
栀梦 2021-02-07 11:41

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

2条回答
  •  南笙
    南笙 (楼主)
    2021-02-07 11:49

    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.

提交回复
热议问题