Yasin Osman
Yasin Osman

Reputation: 93

C++ char to int conversion for numbers greater than 9

I am trying to convert char number values to integers in c++. For example :

char x ='0';
int intX = x-'0';

this works but when i am trying to do the same thing with numbers that are greater than 10 it freaks out. For example :

char onuc = '13';
cout<<int(onuc);

The outpus is 51.

Please help thanks:)

Upvotes: 1

Views: 1673

Answers (2)

Suraj Upadhyay
Suraj Upadhyay

Reputation: 475

What you are actually doing in the second case is to cast a multi-character into an int type. Multi-characters are implemented differently than normal characters, which are nothing but ascii codes. The value of the multi-character '13' would be derived as '1'*256+'3' which is 12592 (I believe it is dependent on the compiler).

For some more examples int('abcd') = 1633837924 is calculated as :

'a'*2563 + 'b'*2562 + 'c'*256 + 'd'

I hope this answer helps you.

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234735

The x - '0' idiom only works since the characters 0 to 9 are arranged in a contiguous block. (The C++ standard requires that).

But '13' is a multicharacter constant with an implementation defined value. It is an int type so your assignment to char is a lossy transformation in general. '1' * 256 + '3' is a common implementation.

So alas this approach doesn't work, something like

int intX = std::stoi("13");

however will.

Upvotes: 6

Related Questions