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.
In C programming language, hexadecimal value is represented as 0x or 0X and to input hexadecimal value using scanf which has format specifiers like %x or %X.
Does atoi work on hex? atoi(s[,base]) converts a string into an integer. The default is decimal, but you can specify octal 8, hexadecimal 16, or decimal 10.
Start with the right-most digit of your hex value. Multiply it by 160, that is: multiply by 1. In other words, leave it be, but keep that value off to the side. Remember to convert alphabetic hex values (A, B, C, D, E, and F) to their decimal equivalent (10, 11, 12, 13, 14, and 15).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With