encoder.c 1.06 KB
#include <stdio.h>
#include <string.h>
#include "auxiliar.h"
#include <math.h>

int check_length(char **inputs, uint8_t num_inputs)
{
    int i;
    for(i = 0; i < num_inputs; i++)
    {
            if(strlen(inputs[i]) != 1)
            {
                    return -1;
            }
    }
    int max_value = 1;
    i = 0;
    while(max_value < num_inputs)
    {
    	max_value = 0x1 << ++i;
    }
    return i;
}

int main(int argc, char **argv)
{
	int i;
	int pos;
	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,',');
	pos = num_inputs - 1;
	int sel_length = check_length(inputs,num_inputs);
	if(sel_length == -1)
	{
		error();
	}
	int selected = -1;
	for(i = 0; i < num_inputs; i++)
	{
		if(inputs[i][0] == '1')
		{
			selected = i;
			break;
		}
	}
	if(selected == -1)
	{
		error();
	}
	char *result = dec2bin(selected,sel_length);
	printf("%s",result);
	free(result);
	free_mem(inputs,num_inputs);
	return 0;
}