简体   繁体   中英

ASCII to decimal value

Consider this below example:

char a  = '4';

int c = (int)a;   // this gives the hex value of '4' which is 0x34

but I want the result 4 as an integer. How to do this? Just a Hex2Dec conversion?

int i = a - '0';
printf("%d",i);

The char values for digits 0 to 9 are contiguous and you make use of that here as shown above.

The characters that represent decimal digits are laid out in ASCII space in numerical order.

  • '0' is ASCII 0x30
  • '1' is ASCII 0x31
  • '2' is ASCII 0x32
  • and so on.

This means that you can simply subtract '0' from your character to get the value you desire.

char a = ...;
if (a >= '0' && a <= '9')
{
    int digit = a - '0';
    // do something with digit
}

USe

char a = '4';     //ASCII value of '4' is 52
int b = a - '0';  // ASCii value of '0' is 48 so 52-48 will return 4.
printf("%d", b);  //It will print 4.
  • ASCII value of 0 [in hex] == 30.
  • ASCII value of 9 [in hex] == 39.

Hope you got the relation. To get the character value as integer , just subtract the ASCII value of 0 from the char variable itself. The difference will be same as the value.

For details, check the ASCII table here .

As example,

char cInput = `4`;
int iInput;

iInput = cInput - `0`;

printf("as integer = %d\n", iInput);

Will print 4 .

ASCII conversion to value for characters in ranges af, AF, or 0-9 can be accomplished with a switch statement, as is used in the following function:

unsigned char convert(unsigned char ch) {
    unsigned char value;
    switch (ch) {
        case 'A' :
        case 'B':
        case 'C':
        case 'D':
        case 'E':
        case 'F': value = ch + 10 - 'A';  break;
        case 'a':
        case 'b':
        case 'c':
        case 'd':
        case 'e':
        case 'f': value = ch + 10 - 'a';  break;
        default: value = ch - '0';
    }
    return value;
}

Some clarifications about your statement

This gives the hex value of '4'

by doing:

char a  = '4';

you put the ASCII value of '4' - which maps to 0x34, in to the one byte variable 'a'.

The action:

int c = (int) a; 

is called casting. what it does is copying the value inside 'a' (one byte) into the value in 'c' (4 bytes). Therefore, the value inside 'c' would be 0x00000034 (the other 3 bytes are initialized to zero).

Finally, when you want to print the value, you could do it in any way you want. printf("%d",c); will give you the decimal value - 52, whereas printf("%x",c); will give you the hexadecimal value.

Cheers,

#include <string.h>

#include void main(){ if(,strcmp(name;"Jan") printf("wellcom Jan"); else printf("Error"); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM