Search code examples
cstringhex

How to convert string to hex value in C


I have string "6A" how can I convert into hex value 6A?

Please help me with solution in C

I tried

char c[2]="6A"
char *p;
int x = atoi(c);//atoi is deprecated 

int y = strtod(c,&p);//Returns only first digit,rest it considers as string and
//returns 0 if first character is non digit char.

Solution

  • The question

    "How can I convert a string to a hex value?"

    is often asked, but it's not quite the right question. Better would be

    "How can I convert a hex string to an integer value?"

    The reason is, an integer (or char or long) value is stored in binary fashion in the computer.

    "6A" = 01101010
    

    It is only in human representation (in a character string) that a value is expressed in one notation or another

    "01101010b"   binary
    "0x6A"        hexadecimal
    "106"         decimal
    "'j'"         character
    

    all represent the same value in different ways.

    But in answer to the question, how to convert a hex string to an int

    char hex[] = "6A";                          // here is the hex string
    int num = (int)strtol(hex, NULL, 16);       // number base 16
    printf("%c\n", num);                        // print it as a char
    printf("%d\n", num);                        // print it as decimal
    printf("%X\n", num);                        // print it back as hex
    

    Output:

    j
    106
    6A