Martin Melichar
Martin Melichar

Reputation: 1156

Numerical operations between int and char in C

I would like to know how are data really stored, because in example beyond is intuition weak.

I believed, that any value has it's numerical recognition; as 'a' has value of 48; so I assumed, that in any situation I can decrement 48 as 'a' (eg. (100 - 'a' == 52)).

Reality seems to be different.

So;

when can I decrement with 'a' to get int-like value? what should I use here, so it would looks like more intuitively?

...

program is barely finished, however function takes array of chars and it needs to get int of value (3) from one of chars. /* for this scenario */

Thank you for help!

/* command reader */
int cr (char a[])
{
    printf("%s\n", a);

    /* command sequence */
    char co[350]; /* <-- change later */

    for (int cri = 0, coi = 0; a[cri]; cri++, coi++)
    {
        printf("%c ", a[cri]);

        co[coi] = a[cri];
    }

    int ec (char co[])
    {
        printf("\n%s co\n", co);
        printf("\n%c co1\n", co[1]);

        co[1] = co[1];

        printf("\n basic: %d\n\n", co[1]); /* 51 */

        co[2] = co[1] - 'a';

        printf("\n charred out: %d\n\n", co[2]); /* -46 */

        co[3] = co[1] - 48;

        printf("\n numbered out: %d\n\n", co[3]); /* 3 */

        return 0;
    }

    ec(co);

    return 0;
}

cr("F3 R B");

Upvotes: 0

Views: 167

Answers (2)

Martin Melichar
Martin Melichar

Reputation: 1156

As WhozCraig said, I was looking for (- "0"), where numeric value of "0" is 48.

Upvotes: 0

Striezel
Striezel

Reputation: 3758

The "value" of 'a', that is its numerical representation, actually depends on the character set. In most cases that is the American Standard Code for Information Interchange (ASCII) or a character set where the first 128 codepoints are identical to ASCII. However, the ASCII value for 'a' is actually 97 and not 48.

Upvotes: 2

Related Questions