tern-assembler/main.c

114 lines
1.9 KiB
C
Raw Normal View History

2023-12-23 18:22:45 +01:00
#include <stdio.h>
2024-02-19 22:25:25 +01:00
#include "asm_rules.c"
2023-12-23 18:22:45 +01:00
2024-03-11 23:09:47 +01:00
void bin_to_hex(char *tryte, char *hex) {
char *a = tryte;
int num = 0;
do {
int b = *a=='1'?1:0;
num = (num<<1)|b;
a++;
} while (*a);
sprintf(hex, "%x", num);
printf("%d\n", num);
}
void trit_to_bin(char *_asm, char opcode, char in0, char in1, char out){
2024-02-29 22:53:11 +01:00
char tryte[54];
2024-03-11 23:09:47 +01:00
char t0[18];
char t1[18];
char t2[18];
char t3[18];
for (int i = 0; i < 18; i++) {
t0[i] = 0;
t1[i] = 0;
t2[i] = 0;
t3[i] = 0;
}
2024-02-29 22:53:11 +01:00
for (int i = 0; i < 54; i++) {
2024-03-11 23:09:47 +01:00
tryte[i] = 0;
2024-02-29 22:53:11 +01:00
}
2023-12-23 18:22:45 +01:00
//convert assembly to formated binary representation of ternary
2024-02-29 22:53:11 +01:00
for (int i = 0; i < 27; i++) {
2023-12-23 18:22:45 +01:00
2024-03-11 23:09:47 +01:00
//printf("%c",_asm[i]);
2024-02-29 22:53:11 +01:00
if(_asm[i]==2) {
strcat(tryte, "10");
} else if (_asm[i]==1) {
strcat(tryte, "01");
2023-12-23 18:22:45 +01:00
} else {
2024-02-29 22:53:11 +01:00
strcat(tryte, "00");
2023-12-23 18:22:45 +01:00
}
}
2024-03-11 23:09:47 +01:00
int j = 0;
for (int i = 0; i < 18; i++) {
t0[i] = tryte[j];
j++;
}
for (int i = 0; i < 18; i++) {
t1[i] = tryte[j];
j++;
}
for (int i = 0; i < 18; i++) {
t2[i] = tryte[j];
j++;
}
for (int i = 0; i < 18; i++) {
t3[i] = tryte[j];
j++;
}
2024-02-29 22:53:11 +01:00
2024-03-11 23:09:47 +01:00
bin_to_hex(t0, &opcode);
bin_to_hex(t1, &in0);
bin_to_hex(t2, &in1);
bin_to_hex(t3, &out);
2023-12-23 18:22:45 +01:00
}
int main() {
FILE *dest_asm = fopen("assembly.txt", "w");
FILE *src_asm = fopen("src.asm", "r");
2024-02-19 22:25:25 +01:00
unsigned int size=0;
2023-12-23 18:22:45 +01:00
fprintf(dest_asm,"00000\n");
2024-03-11 23:09:47 +01:00
char in_asm[64];
2024-02-29 22:53:11 +01:00
char out_asm[27];
2024-03-11 23:09:47 +01:00
char hex_op[5];
char hex_in0[5];
char hex_in1[5];
char hex_out[5];
fgets(in_asm, 64, src_asm);
2023-12-23 18:22:45 +01:00
2024-02-19 22:25:25 +01:00
while(!feof(src_asm)) {
2023-12-23 18:22:45 +01:00
2024-02-19 22:25:25 +01:00
asm_rules(in_asm, out_asm);
2024-03-11 23:09:47 +01:00
trit_to_bin(out_asm, *hex_op, *hex_in0, *hex_in1, *hex_out);
2023-12-23 18:22:45 +01:00
2024-03-11 23:09:47 +01:00
fprintf(dest_asm,"%.5s ", hex_op);
fprintf(dest_asm,"%.5s ", hex_in0);
fprintf(dest_asm,"%.5s ", hex_in1);
fprintf(dest_asm,"%.5s \n", hex_out);
2023-12-23 18:22:45 +01:00
// Write the hex to a file
2024-02-19 22:25:25 +01:00
2024-03-11 23:09:47 +01:00
fgets(in_asm, 64, src_asm);
2024-02-19 22:25:25 +01:00
size++;
2023-12-23 18:22:45 +01:00
}
printf("\n%u trytes", size);
// Close the file
fclose(dest_asm);
fclose(src_asm);
return 0;
}