# Pelles C forum

## C language => Tips & tricks => Topic started by: TimoVJL on May 02, 2016, 06:27:56 pm

Title: Hex2Int() example
Post by: TimoVJL on May 02, 2016, 06:27:56 pm
Ispired by masm32 forum topic here (http://masm32.com/board/index.php?topic=5323.msg57148#msg57148)
Code: [Select]
`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;}`
Title: Re: Hex2Int() example
Post by: jj2007 on May 07, 2016, 08:37:52 am
Hi Timo,
Does this work for you? I always get zero...

Code: [Select]
`#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();}`
Title: Re: Hex2Int() example
Post by: TimoVJL on May 07, 2016, 09:06:45 am
My mistake :(
value check should be
Code: [Select]
`...else if (ch < 0 || ch > 16) break;...`not
Code: [Select]
`else break;`