tern-assembler/main.c
2024-03-12 10:18:56 +01:00

119 lines
1.9 KiB
C

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