Implement own atoi() for A-type instruction parser
x1phosura x1phosura@x1phosura.zone
Sat, 26 Nov 2022 19:21:22 -0800
1 files changed,
13 insertions(+),
16 deletions(-)
M
projects/06/assembler1/assembler1.c
→
projects/06/assembler1/assembler1.c
@@ -6,7 +6,7 @@ #include <string.h>
#include "../bindump.h" -#define DEBUG(...) printf(__VA_ARGS__) +#define DEBUG(...) printf(__VA_ARGS__) #define die(err_msg, exit_val) perror(err_msg); exit(exit_val) #define alert(...) fprintf(stderr, __VA_ARGS__)@@ -14,10 +14,14 @@
uint32_t myatoi(const char *a_field_str) { - DEBUG("a_field_str = %s\n", a_field_str); - // I know, I could just use atoi(), but where's the fun in that? - // STUB - return 0xaff; + size_t i; + uint32_t ret = 0; + + for (i = 0; i < 5 && '0' <= a_field_str[i] && a_field_str[i] <= '9'; ++i) { + ret = (ret * 10) + (a_field_str[i] - 0x30); + } + + return ret; } bool parse_a_type(const char *line, uint16_t *instruction)@@ -84,7 +88,7 @@ }
// does not care about line line length; exits at first newline or after // relevant portion parsed (allows for syntactically-incorrect lines, I know) -bool parse_instruction_w_type(const char *line, uint16_t *instruction) +bool parse_next_instruction(const char *line, uint16_t *instruction) { bool ret; char c;@@ -100,7 +104,8 @@ } else if (c >= '!' && c < '~') {
ret = parse_c_type(line, instruction); break; } else { - die("error: TODO explain...\n", -1); + alert("syntax error: line '%s' incorrectly formatted\n", + line); } ++i;@@ -109,15 +114,7 @@
return ret; } -bool parse_next_instruction(const char *line, uint16_t *instruction) -{ - *instruction = 1337; // STUB, should be 0x539, 0b0000010100111001 - return parse_instruction_w_type(line, instruction); - - return true; -} - -/* return false for comment or invalid assembly instruction */ +// return false for comment or invalid assembly instruction bool parse_line(const char *line, size_t line_len, uint16_t *instruction) { char c;