langatator/src/operate.c
Matthieu Bessat a62dd411aa feat(Evaluator): add pow operator
feat(Evaluator): add minus sign reducing
fix(Evaluator): trim spaces
test: add base for unit testing
2022-04-30 16:16:37 +02:00

84 lines
2 KiB
C

#include <stdio.h>
#include <string.h>
#include "./operate.h"
#include "./types.h"
#include "./utils.h"
int is_operator(char candidate) {
return (
candidate == '*' ||
candidate == '/' ||
candidate == '+' ||
candidate == '-' ||
candidate == '^'
);
}
int operate(
unsigned char operator,
unsigned char typeA, int aRepr,
unsigned char typeB, int bRepr,
unsigned char* typeRes, int* resPtr
)
{
if (
typeA == TYPE_FLOAT || typeB == TYPE_FLOAT ||
operator == '/'
) {
*typeRes = TYPE_FLOAT;
float a, b, res;
if (typeA == TYPE_FLOAT) {
*((int*) &a) = aRepr;
}
if (typeB == TYPE_FLOAT) {
*((int*) &b) = bRepr;
}
if (typeA == TYPE_INT) {
a = (float) aRepr;
}
if (typeB == TYPE_INT) {
b = (float) bRepr;
}
printf("Appling operation: %f %c %f \n", a, operator, b);
if (operator == '+') {
res = a+b;
} else if (operator == '-') {
res = a-b;
} else if (operator == '*') {
res = a*b;
} else if (operator == '/') {
res = a/b;
} else if (operator == '^') {
res = 0;
} else {
return 2;
}
printf("Got float: %f \n", res);
// get int representation of float
*resPtr = *(int *)(&res);
return 0;
}
if (typeA == TYPE_INT && typeB == TYPE_INT) {
printf("Appling operation %d %c %d \n", aRepr, operator, bRepr);
*typeRes = TYPE_INT;
int res = 0;
if (operator == '+') {
res = aRepr+bRepr;
} else if (operator == '-') {
res = aRepr-bRepr;
} else if (operator == '*') {
res = aRepr*bRepr;
} else if (operator == '^') {
res = integer_pow(aRepr, bRepr);
} else {
return 2;
}
*resPtr = res;
return 0;
}
return 3;
}