shifter.c 2.1 KB
#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;
}