Blame view

arith/substractor.c 1.03 KB
Imanol-Mikel Barba Sabariego authored
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
#include <stdio.h>
#include <string.h>
#include "auxiliar.h"

int check_length(char **inputs, uint8_t num_inputs)
{
	int input_length = strlen(inputs[0]);
    if((input_length != strlen(inputs[1])) || (strlen(inputs[2]) != 1))
    {
    	return -1;
    }
    return input_length;
}

int main(int argc, char **argv)
{
	if(argc != 2)
	{
		error();
	}
	char *input = argv[1];
	if(!strcmp(input,"error"))
	{
		error();
	}
	char **inputs = comma_separate(input);
	if(inputs == NULL)
	{
		error();
	}
	int num_inputs = num_occurrences(input,',');
	if(num_inputs != 3)
	{
		error();
	}
	int input_length = check_length(inputs,num_inputs);
	if(input_length == -1)
	{
		error();
	}
	int a,b,borrow_in,c;
	char borrow_out = '0';
Imanol-Mikel Barba Sabariego authored
43
44
45
	a = bin2udec(inputs[0]);
	b = bin2udec(inputs[1]);
	borrow_in = bin2udec(inputs[2]);
Imanol-Mikel Barba Sabariego authored
46
47
48
49
50
51
52
53
54
55
56
	c = a-(b+borrow_in);
	if(c < 0)
	{
		borrow_out = '1';
	}
	char *result = dec2bin(c,input_length);
	printf("%s,%c",result,borrow_out);
	free(result);
	free_mem(inputs,num_inputs);
	return 0;
}