summaryrefslogtreecommitdiff
path: root/lib/numbers.c
blob: ba45f2948b8d1b99b2f4c5adbf973b72859800be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "global.h"
#include "numbers.h"

int char_to_number(char *st, int *valid)
{
	int whattype = 0, result = 0;
	
	*valid = 0;
	
	if (*st == '0') {
		st++;
		if (*st == 'x') {
			whattype = 1;
			st++;
		} else if (*st) {
			whattype = 2;
		} else {
			*valid = 1;
			return 0;
		}
	}
	
	while (*st) {
		switch (whattype) {
		case 0:
			if ((*st < '0') || (*st > '9')) {
				return 0;
			}
			result *= 10;
			result += *st - '0';
			break;
		case 1:
			if (((*st < '0') || (*st > '9')) && ((*st < 'A') || (*st > 'F'))
			    && ((*st < 'a') || (*st > 'f'))) {
				return 0;
			}
			result *= 16;
			if ((*st >= '0') && (*st <= '9')) {
				result += *st - '0';
			} else if ((*st >= 'A') && (*st <= 'F')) {
				result += *st - 'A' + 10;
			} else {
				result += *st - 'a' + 10;
			}
			break;
		case 2:
			if ((*st < '0') || (*st > '7')) {
				return 0;
			}
			result *= 8;
			result += *st - '0';
			break;
		}
		st++;
	}
	
	*valid = 1;
	return result;
}