Tomasz
Tomasz

Reputation: 29

Trying to convert a string/char to an integer yielded an unexpected result

I came across something strange. It is probably trivial but I can't find the answer. Can anyone explain to me why in this action I get a result of 49?

using namespace std;

int main() {
    int number;
    string binary = "10101011";

    number = int(binary[0]);
    cout << number; // result is 49 , why is that?    
}

Upvotes: 0

Views: 85

Answers (4)

Akhil Pathania
Akhil Pathania

Reputation: 752

So actually in your code you are not printing that char in int but rather than you are printing ASCII value of '1' that is 49.

Whenever a char is converted to int it changes and assigns ASCII value of that char.

to solve your problem you can use folow:

#define conv_digit(ch) (ch-'0') 

Then just call this function passing binary[0] or whatever char you want.

Upvotes: 0

QuentinUK
QuentinUK

Reputation: 3077

binary[0] is '1', which has an ASCII value of 49.

Upvotes: 4

Yevhenii Mamontov
Yevhenii Mamontov

Reputation: 194

Because when you're trying to convert binary[0] element, which is of char type to int type - it converts char's ASCII code that is simply a number, as it was mentioned by @QuentinUK.

If you want to store bits and convert them to numbers, you should look at std::bitset.

If you want to get any element out of std::string as a number, you should look at std::atoi.

Upvotes: 1

Aditya Nagesh
Aditya Nagesh

Reputation: 300

You have defined string binary = "10101011"; binary[0] is character '1'. When you parse a character to int, the output is ASCII value of the character.

Upvotes: 0

Related Questions