SingingCat 0
application
ascii_parser.c
1#include "main-header.h"
2// #include "bare-metal.h"
3
4int atoi(const char *s) {
5 int res = 0;
6
7 if (s == NULL) {
8 return 0;
9 }
10 int pos = 0;
11
12 while (s[pos] != 0) {
13 int z = ascii_parse_num(s[pos]);
14 if (z == -1) {
15 return res;
16 }
17 res = res * 10;
18 res = res + z;
19 pos++;
20 }
21 return res;
22}
23
24byte atoh(const char *s) {
25 int x, y;
26
27 x = charToHex(s[0]);
28 if (x == -1) {
29 return 0;
30 }
31 y = charToHex(s[1]);
32 if (y == -1) {
33 return 0;
34 }
35 int r = (x << 4) + y;
36
37 return (byte)r;
38}
39
40
41int ascii_parse_num(int b) {
42 if ((b < '0') || (b > '9')) {
43 return -1;
44 }
45 return b - '0';
46}
47int ascii_parse_int(const byte *buf, int size, int *const newpos) {
48 int res = 0;
49 int consumed = 0;
50
51 if (size <= 0) {
52 *newpos = 0;
53 CNWDEBUG("attempt to parse ascii int with size %i\r\n", size);
54 return -1;
55 }
56 while (consumed < size) {
57 int b = ascii_parse_num(buf[consumed]);
58 if (b < 0) {
59 *newpos = consumed;
60 return res;
61 }
62 res = res * 10 + b;
63 consumed++;
64 }
65 *newpos = consumed;
66 return res;
67}
71long ascii_parse_hex(const byte *buf, int size, int *newpos) {
72 int consumed = 0;
73 long res = 0;
74
75 if (newpos != NULL) {
76 *newpos = -1;
77 }
78 if (size <= 0) {
79 if (newpos != NULL) {
80 *newpos = 0;
81 }
82 CNWDEBUG("attempt to parse ascii hex with size %i\r\n", size);
83 return -1;
84 }
85 while (consumed < size) {
86 int t = charToHex(buf[consumed]);
87 if (t < 0) {
88 if (newpos != NULL) {
89 *newpos = consumed;
90 }
91 // CNWDEBUG("1 Hex parser: %li [%i,%i] (%s)\r\n",res,consumed,t,(char *)&buf[consumed]);
92 return res;
93 }
94 res = (res << 4) | t;
95 consumed++;
96 }
97 //CNWDEBUG("2 Hex parser: %li [%i] (%s)\r\n",res,consumed,(char *)&buf[consumed]);
98 if (newpos != NULL) {
99 *newpos = consumed;
100 }
101 return res;
102}