-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbf2c.py
executable file
·60 lines (54 loc) · 977 Bytes
/
bf2c.py
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
#!/usr/bin/env python3
import sys
HEADER = '''\
#include <stdio.h>
unsigned char mem[0x10000];
int main(void) {
unsigned char *ptr = mem;
int chr;
'''
FOOTER = '''\
return 0;
}
'''
GT = '''\
++ptr;
'''
LT = '''\
--ptr;
'''
PLUS = '''\
++*ptr;
'''
MINUS = '''\
--*ptr;
'''
DOT = '''\
putchar(*ptr);
'''
COMMA = '''\
*ptr = (chr = getchar()) != EOF ? chr : 0;
'''
LBRACKET = '''\
while (*ptr) {
'''
RBRACKET = '''\
}
'''
COMMANDS = {'>': GT, '<': LT, '+': PLUS, '-': MINUS, '.': DOT, ',': COMMA,
'[': LBRACKET, ']': RBRACKET}
def bf2c(code):
ccode = [HEADER]
for c in code:
comm = COMMANDS.get(c)
if comm:
ccode.append(comm)
ccode.append(FOOTER)
return ''.join(ccode)
if __name__ == '__main__':
file = sys.stdin
if len(sys.argv) >= 2 and sys.argv[1] != '-':
file = open(sys.argv[1])
code = file.read()
ccode = bf2c(code)
sys.stdout.write(ccode)