Reputation: 29
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
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
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
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