Ispired by masm32 forum topic here (http://masm32.com/board/index.php?topic=5323.msg57148#msg57148)
int Hex2Int(char *s)
{
int n = 0;
unsigned char ch;
while (*s) {
ch = *s - '0';
if (ch >= 49 && ch <= 55) ch -= 39; // 'a' - '0'
else if (ch >= 17 && ch <= 22) ch -= 7; // 'A' - '0'
else if (ch < 0 || ch > 16) break;
n = n<<4;
n += ch;
s++;
}
return n;
}
Hi Timo,
Does this work for you? I always get zero...
#include <stdio.h>
#pragma warn(disable:2216) // retval never used
#pragma warn(disable:2007) // assembly not portable
#pragma warn(disable:2018) // _getch
#pragma comment(linker, "/subsystem:console" )
int Hex2Int(char *s)
{
int n = 0;
unsigned char ch;
// _asm int 3;
while (*s) {
ch = *s - '0'; /// <- sure?
if (ch >= 49 && ch <= 55) ch -= 39; // 'a' - '0'
else if (ch >= 17 && ch <= 22) ch -= 7; // 'A' - '0'
else break;
n = n<<4;
n += ch;
s++;
}
return n;
}
int main(void) {
printf("%i\n", Hex2Int("123h"));
_getch();
}
My mistake :(
value check should be
...
else if (ch < 0 || ch > 16) break;
...
notelse break;