### Author Topic: Hex2Int() example  (Read 3389 times)

#### TimoVJL

• Global Moderator
• Member
• Posts: 1975
##### Hex2Int() example
« on: May 02, 2016, 06:27:56 pm »
Ispired by masm32 forum topic here
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;}`
« Last Edit: May 07, 2016, 09:04:27 am by TimoVJL »
May the source be with you

#### jj2007

• Member
• Posts: 516
##### Re: Hex2Int() example
« Reply #1 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();}`

#### TimoVJL

• Global Moderator
• Member
• Posts: 1975
##### Re: Hex2Int() example
« Reply #2 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;`
May the source be with you