News:

Download Pelles C here: http://www.smorgasbordet.com/pellesc/

Main Menu

Hex2Int() example

Started by TimoVJL, May 02, 2016, 06:27:56 PM

Previous topic - Next topic

TimoVJL

Ispired by masm32 forum topic here
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;
}
May the source be with you

jj2007

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();
}


TimoVJL

My mistake :(
value check should be
...
else if (ch < 0 || ch > 16) break;
...
notelse break;
May the source be with you