27

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.
8
  • 1
    By using val=strtol(string, NULL, 16); It returns a long type so you might need to check/cast it. Commented Apr 9, 2015 at 19:22
  • 2
    Does not desrve downvote.Its genuine question. Commented Apr 9, 2015 at 19:24
  • 1
    @mah Hope that satisfies purpose now. Commented Apr 9, 2015 at 19:37
  • @SteveFenton Thanks,But I needed solution in C not obj-C. Commented Apr 9, 2015 at 19:39
  • 1
    char c[2]="6A" is a problem. should be char c[]="6A" or char c[3]="6A". c is not a string unless it has a terminating null character. Commented Apr 9, 2015 at 20:40

2 Answers 2

65

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
Sign up to request clarification or add additional context in comments.

Comments

0

For converting string to hex value, and storing to variable:

char text[20] = "hello friend";

int text_len = strlen(text);
char *hex_output = malloc(text_len*2 + 1); // 2 hex = 1 ASCII char + 1 for null char

if (hex_output == NULL)
{
        perror("Failed to allocated memory.");
        return 1;
}

int hex_index = 0;

for (int i = 0; i < strlen(text); i++)
{
        char t = text[i];

        int w = sprintf(&hex_output[hex_index], "%x", t);

        if (w < 0)
        {
                perror("Failed to convert to hex.");
                return 1;
        }

        hex_index += 2;
}

hex_output[strlen(hex_output)] = 0x0;
printf("%s\n", hex_output);

Output:

68656c6c6f20667269656e64

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.