user900785
user900785

Reputation: 423

Convert to ASCII String from hex String in C

I am trying to convert a hex string to its equivalent ASCII. I am given a "hex" value of a string as a string, i.e instead of "ABCD" I get "41424344". I just need to extract 41 which will be my hexvalue and recode as "ABCD". Here is what I have.

   int main(int argc, char *argv[]){

    char *str = "ABCD";
    unsigned int val = 0;
    int i = 0;
    int MAX = 4;
    for (i = 0; i<MAX; i++){
        val = (str[i] & 0xFF);
        //printf("dec val= %d\n", val);
        //printf("hex val= %02x\n", val);
    }
    val = 0;
    char *hexstr = "41424344";
    char *substr = (char*)malloc(3);
    char *ptr = hexstr;

    for (i = 0; i<8; i++){
        strncpy(substr, ptr, 2);
        printf("substr = %s\n", substr);
        int s = atoi(substr);
        printf("s= %d\n", s);
        ptr= ptr+2;
        i = i+2;
    }
    return 0;

}

The thing is from here on, I have to make this "s" value to be a hex value and not an int. How can this be done?

UPDATE:

Here is what I have after your answers:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){

    char *str = "ABCD";
    unsigned int val;
    val = 0;
    int i = 0;
    int MAX = 4;
    for (i = 0; i<MAX; i++){
        val = (str[i] & 0xFF);
        //printf("dec val= %d\n", val);
        //printf("hex val= %02x\n", val);
    }
    val = 0;
    char *hexstr = "41424344";
    char *substr = (char*)malloc(3);
    char *ptr = hexstr;
    char *retstr = (char *)malloc(5);
    char *retptr = retstr;

    for (i = 0; i<8; i+1){
        strncpy(substr, ptr, 2);
        printf("substr = %s\n", substr);
        int s = strtol(substr, NULL, 16);
        printf("s= %d\n", s);
        ptr= ptr+2;
        i = i+2;
        sprintf(retptr, "%c", s);
        retptr = retptr +1;
    }
    printf("retstr= %s\n", retstr);
    return 0;

}

Upvotes: 1

Views: 14106

Answers (1)

slaterade
slaterade

Reputation: 454

Change your "s" variable line from

int s = atoi(substr);

to

int s = strtol(substr, NULL, 16);

Upvotes: 2

Related Questions