Reputation: 865
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.
Upvotes: 26
Views: 139857
Reputation: 608
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
Upvotes: 0
Reputation: 34575
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
Upvotes: 64