Raneesh
Raneesh

Reputation: 29

I am not able to understand the concept how string is converted to integers

I referred a program for time conversion and not able to understand some part of the code. Here's the full program.

#include<iostream>
#include<cstdio>

using namespace std;

int main() {
    string s;
    cin >> s;

    int n = s.length();
    int hh, mm, ss;
    hh = (s[0] - '0') * 10 + (s[1] - '0');
    mm = (s[3] - '0') * 10 + (s[4] - '0');
    ss = (s[6] - '0') * 10 + (s[7] - '0');

    if (hh < 12 && s[8] == 'P') hh += 12;
    if (hh == 12 && s[8] == 'A') hh = 0;

    printf("%02d:%02d:%02d\n", hh, mm, ss);

    return 0;
}

The part of code i am not able to understand is

    hh = (s[0] - '0') * 10 + (s[1] - '0');
    mm = (s[3] - '0') * 10 + (s[4] - '0');
    ss = (s[6] - '0') * 10 + (s[7] - '0');

Thanks in advance.

Upvotes: 2

Views: 103

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409136

If you see e.g. this ASCII table (ASCII being the most common character encoding scheme) you can see that the character '2' has the decimal value 50, and that the character '0' has the decimal value 48.

Considering that a character is just really a small integer, we can use normal arithmetic on them. That means if you do e.g. '2' - '0' that's the same as doing 50 - 48 which results in the decimal value 2.

So to get the decimal value of a character digit, just subtract '0'.

The multiplication with 10 is because we're dealing with the decimal system, where a number such as 21 is the same as 2 * 10 + 1.


It should be noted that the C++ specification explicitly says that all digits have to be encoded in a contiguous range, so it doesn't matter which encoding is used this will always work.

You might see this "trick" being used to get a decimal value for letters as well, but note that the C++ specification doesn't say anything about that. In fact there are encodings where the range of letters is not contiguous and where this will not work. It's only specified to work on digits.

Upvotes: 6

Blasco
Blasco

Reputation: 1735

In the ASCCI encoding numbers are encoded sequentially. This is:

'0' has the value 48

'1' has the value 49

'2' has the value 50

etc

Therefor, 'x' - '0' == x from '0' to '9'

For example:

if you have your string 12:23:53 we have:

hh = (s[0] - '0') * 10 + (s[1] - '0');

(s[0] - '0') means '1'-'0' which is equal to 1, but this is the ten, so *10 + (s[1] - '0') which is '2'-'0', so 2. In total 12.

Same thing for the minutes and seconds.

Upvotes: 2

Related Questions