Blame view

arith/shifter.c 2.1 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include <stdio.h>
#include <string.h>
#include "auxiliar.h"

#define LEFT  	0
#define RIGHT 	1
#define LOGIC 	0
#define ARITH 	1
#define ROTATE 	2

int main(int argc, char **argv)
{
	uint8_t direction, type;
	int shift;
	if(argc != 3)
	{
		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 != 2)
	{
		error();
	}
	int input_length = strlen(inputs[0]);
	if(!strcmp("logic-left",argv[2]))
	{
		type = LOGIC;
		direction = LEFT;
	}
	else if(!strcmp("logic-right",argv[2]))
	{
		type = LOGIC;
		direction = RIGHT;
	}
	else if(!strcmp("arith-left",argv[2]))
	{
		type = ARITH;
		direction = LEFT;
	}
	else if(!strcmp("arith-right",argv[2]))
	{
		type = ARITH;
		direction = RIGHT;
	}
	else if(!strcmp("rotate-left",argv[2]))
	{
		type = ROTATE;
		direction = LEFT;
	}
	else if(!strcmp("rotate-right",argv[2]))
	{
		type = ROTATE;
		direction = RIGHT;
	}
	else
	{
		error();
	}
	shift = bin2udec(inputs[1]);
	while(shift >= input_length)
	{
		shift = shift % input_length;
	}
	char *result;
	if(!shift)
	{
		result = inputs[0];
	}
	else
	{
		if(type == LOGIC)
		{
			if(direction == LEFT)
			{
				result = dec2bin(bin2udec(inputs[0]) << shift,input_length);
			}
			else
			{
				result = dec2bin(bin2udec(inputs[0]) >> shift,input_length);
			}
		}
		else if(type == ARITH)
		{
			if(direction == LEFT)
			{
				result = dec2bin(bin2dec(inputs[0]) << shift,input_length);
			}
			else
			{
				result = dec2bin(bin2dec(inputs[0]) >> shift,input_length);
			}
		}
		else if(type == ROTATE)
		{
			if(direction == RIGHT)
			{
				shift = input_length - shift;
			}
			result = (char*) malloc(sizeof(char) * (input_length+1));
			memset(result,0x00,input_length);
			strncpy(result,inputs[0]+shift,input_length-shift);
			strncpy(result + (input_length-shift),inputs[0],shift);
		}
	}
	printf("%s",result);
	free(result);
	free_mem(inputs,num_inputs);
	return 0;
}