Blame view

plexers/bit_selector.c 1.6 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
#include <stdio.h>
#include <string.h>
#include "auxiliar.h"
#include <math.h>

int check_length(char **inputs, int num_inputs, int output_length)
{
	int input_length = strlen(inputs[0]);
	int selector_length = strlen(inputs[1]);
	int sel_combinations = 0x1 << selector_length;
	int num_groups = ceil(((float)input_length)/output_length);
	int required_combinations = 1;
    int i = 0;
    while(required_combinations < num_groups)
    {
    	required_combinations = 0x1 << ++i;
    }
	if(sel_combinations < required_combinations)
	{
		return -1;
	}
	return required_combinations * output_length;
}

int main(int argc, char **argv)
{
	int i;
	int j;
	if(argc != 3)
	{
		error();
	}
	char *input = argv[1];
	int output_length = str2int(argv[2]);
	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]);
	int required_length = check_length(inputs,num_inputs,output_length);
	if(required_length == -1)
	{
		error();
	}
	if(input_length != required_length)
	{
		expand_input(&inputs[0],required_length);
	}
Imanol-Mikel Barba Sabariego authored
59
	char *result = (char*) malloc(sizeof(char) * (output_length + 1));
Imanol-Mikel Barba Sabariego authored
60
61
62
63
64
65
66
67
68
69
70
71
72
	memset(result,0x00,output_length+1);
	int selected = bin2dec(inputs[1]);
	int pos = 0;
	for(i = (selected+1)*(output_length)-1; i >= selected*output_length; i--)
	{
		result[pos++] = inputs[0][required_length-(i+1)]; 
	}
	printf("%s",result);
	free(result);
	free_mem(inputs,num_inputs);
	return 0;
}