This source file includes following definitions.
- n2word
- h2word
- addcerrlist_word
- nh2word
- word2n
- word2bit
- print_dumpword
1 #include <stdio.h>
2 #include <string.h>
3 #include <assert.h>
4 #include <stdlib.h>
5 #include <ctype.h>
6
7 #include "word.h"
8 #include "cerr.h"
9
10
11
12
13
14
15
16
17 WORD n2word(const char *str);
18
19
20
21
22
23
24
25
26 WORD h2word(const char *str);
27
28 WORD n2word(const char *str)
29 {
30 assert(isdigit(str[0]) || str[0] == '-');
31
32 char *check = NULL;
33 int n;
34
35 n = strtol(str, &check, 10);
36 if(check[0]) {
37 setcerr(114, str);
38 return 0x0;
39 }
40
41 if(n < -32768 || n > 32767) {
42 n &= 0xFFFF;
43 }
44 return (WORD)n;
45 }
46
47 WORD h2word(const char *str)
48 {
49 assert(str[0] == '#');
50
51 WORD w = 0;
52 char *check = NULL;
53 str++;
54 if(*str == '-' || strlen(str) > 4) {
55 setcerr(116, str-1);
56 return 0x0;
57 }
58
59 w = (WORD)strtol(str, &check, 16);
60 if(check[0]) {
61 setcerr(115, str-1);
62 return 0x0;
63 }
64 return w;
65 }
66
67
68
69
70 static CERR cerr_word[] = {
71 { 114, "not integer" },
72 { 115, "not hex" },
73 { 116, "out of hex range" },
74 };
75
76
77 void addcerrlist_word()
78 {
79 addcerrlist(ARRAYSIZE(cerr_word), cerr_word);
80 }
81
82 WORD nh2word(const char *str)
83 {
84 WORD w;
85
86 assert(sizeof(WORD) * 8 == 16);
87 if(str == NULL) {
88 return 0x0;
89 }
90 if(!isdigit(*str) && *str != '-' && *str != '#') {
91 setcerr(114, str);
92 return 0x0;
93 }
94 if(*str == '#') {
95 w = h2word(str);
96 } else {
97 w = n2word(str);
98 }
99 return w;
100 }
101
102 char *word2n(WORD word)
103 {
104 enum {
105 MAXLEN = 5,
106 };
107 char *s = malloc_chk(MAXLEN + 1, "word2n.n");
108 char *t = NULL;
109 int d = 0;
110
111 do{
112 s[d++] = word % 10 + '0';
113 } while((word /= 10) > 0);
114 s[d] = '\0';
115 t = strrev(s);
116 FREE(s);
117 return t;
118 }
119
120 char *word2bit(const WORD word)
121 {
122 enum {
123 MAXLEN = 16,
124 };
125 WORD mask = 0x8000;
126 char *bit = NULL;
127 int i = 0;
128
129 bit = malloc_chk(MAXLEN + 1, "word2bit.bit");
130 do {
131 bit[i++] = (word & mask) ? '1' : '0';
132 } while((mask >>= 1) > 0);
133 bit[i] = '\0';
134 return bit;
135 }
136
137 void print_dumpword(WORD word, bool logicalmode)
138 {
139 char *bit = word2bit(word);
140
141 if(logicalmode == true) {
142 fprintf(stdout, "%6u", word);
143 } else {
144 fprintf(stdout, "%6d", (signed short)word);
145 }
146 fprintf(stdout, " = #%04X = %s", word, bit);
147
148 if(word >= 0x20 && word <= 0x7E) {
149 fprintf(stdout, " = \'%c\'", word);
150 } else if(word == 0xA) {
151 fprintf(stdout, " = \'\\n\'");
152 } else if(word == '\t') {
153 fprintf(stdout, " = \'\\t\'");
154 }
155 FREE(bit);
156 }