Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

atoi() from hex representation string

Tags:

c

atoi

Need to make int from hex representation string like "0xFA" or better "FA". Need something like atoi("FA"). Is there are any standard solutions for that?

like image 592
vico Avatar asked Dec 18 '13 09:12

vico


People also ask

Does atoi work for hex?

The atoi() and atol() functions convert a character string containing decimal integer constants, but the strtol() and strtoul() functions can convert a character string containing a integer constant in octal, decimal, hexadecimal, or a base specified by the base parameter.

How do I convert a char to hex then store it to a variable in C?

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. By using val=strtol(string, NULL, 16); It returns a long type so you might need to check/cast it.

Do not use atoi () better use strtol ()?

The atoi() function is subsumed by strtol() but is retained because it is used extensively in existing code. If the number is not known to be in range, strtol() should be used because atoi() is not required to perform any error checking.

Is atoi deprecated?

atoi is not deprecated, your source is incorrect. Nothing in the current C standard ISO 9899:2011 indicates this (see for example chapter 6.11 future language directions), nor anything in earlier standards. As per the C standard, atoi is equivalent to strtol as follows, C11 7.22.


1 Answers

Try to use strtol():

strtol("FA", NULL, 16); 
like image 180
V-X Avatar answered Sep 18 '22 13:09

V-X