-
Notifications
You must be signed in to change notification settings - Fork 0
/
braille.c
76 lines (65 loc) · 1.77 KB
/
braille.c
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
unsigned char convert(unsigned char c)
{
return (c & 0x40) << 1
| (c & 0x07) << 4
| (c & 0x80) >> 4
| (c & 0x38) >> 3;
}
void execute(unsigned char *tape, size_t dp)
{
unsigned char insn, arg;
size_t ip = 0;
while (++ip) {
insn = tape[ip] & 0xf0;
arg = tape[ip] & 0x0f;
switch (insn) {
case 0x00: exit(arg); break;
case 0x10: *tape += tape[dp + arg]; break;
case 0x20: *tape -= tape[dp + arg]; break;
case 0x30: tape[dp + arg] = *tape; break;
case 0x40: *tape = tape[dp] + arg; break;
case 0x50: dp += 1 << arg; break;
case 0x60: dp -= 1 << arg; break;
case 0x70: ip += arg + 1; break;
case 0x80: ip -= arg + 2; break;
case 0x90: if (!*tape) ip += arg + 1; break;
case 0xa0: if (!*tape) ip -= arg + 2; break;
case 0xb0: if (*tape) ip += arg + 1; break;
case 0xc0: if (*tape) ip -= arg + 2; break;
case 0xd0: tape[dp + arg] = getchar(); break;
case 0xe0: putchar(tape[dp + arg]); break;
case 0xf0: tape[dp + arg] = rand() >> 7; break;
}
}
}
int main(int argc, char **argv)
{
int c;
FILE *src;
size_t cap = 1, len = 1;
unsigned char *tape = calloc(1, 1);
if (argc != 2)
return fprintf(stderr, "Usage: %s FILE\n", *argv);
if (!(src = fopen(argv[1], "r")))
return fprintf(stderr, "Unable to open file '%s'\n", argv[1]);
while ((c = fgetc(src)) != EOF) {
if (c == 0xe2) {
int c2 = fgetc(src); if(c2 == EOF) break;
int c3 = fgetc(src); if(c3 == EOF) break;
if(c2 >= 0xa0 && c2 <= 0xa3) { /* found Braille character */
c = convert((c2 - 0xa0) * 0x40 + (c3 - 0x80));
if (cap == len)
tape = realloc(tape, cap <<= 1);
tape[len++] = c;
}
}
}
srand((intptr_t) &c);
execute(tape, len);
fclose(src);
free(tape);
return 0;
}