79 lines
1.8 KiB
C
79 lines
1.8 KiB
C
|
#include "./operate.h"
|
||
|
#include "./types.h"
|
||
|
#include <stdio.h>
|
||
|
#include <string.h>
|
||
|
|
||
|
int is_operator(char candidate) {
|
||
|
return (
|
||
|
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 {
|
||
|
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 {
|
||
|
return 2;
|
||
|
}
|
||
|
*resPtr = res;
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
return 3;
|
||
|
}
|