Converting Decimal number into binary array

I'm working on a Genetic Algorithmic program and now I'm trying to convert decimal number into binary array.

I've written this code to do that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  float D = GA_pop [0][0];
	int k, h;
	int bin [r];
	k = (D -20) /c;
	
	for (column = 0; column < r; column ++){
			if ((k%2) != 0){
				bin [column] = 1;
				h = k/2;
			}
			else if ((k%2) == 0){
				bin [column] = 0;
				h = k/2;
			}
			k=h;
		}


That works but I'm trying to make a function. Here is the function:
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
int dec2bin (float dec, int mod_type){
	int Emin, Emax, column;
	float h;
	if (mod_type == 1){
		Emin = 20; Emax = 20000;
	} else if (mod_type == 2){
		Emin = 20; Emax = 6000;
	} else if (mod_type == 3){
		Emin = 20; Emax = 300;
	}

	int r = ceil (log10 ((Emax - Emin)*pow(10, 4))/log10 (2));
	float c = ((Emax - Emin)/(pow (2,r)-1));
	int bin [r];
	
	int k = (dec - Emin)/c;
	column =0;
	while (column <r){
			if ((k%2) != 0){
				bin [column] = 1;
				h = k/2;
				column ++;
			}
			else if ((k%2) == 0){
				bin [column] =0;
				h = k/2;
				column ++;
			}
			
			k=h;
		}
	return *bin;
}


That function doesn't work. Can anyone tell me what the problem is?
> That function doesn't work
Be more explicit.

int bin [r]; illegal, array size must be constant.
int dec2bin (float dec, int mod_type) returns 1 integer, I thought that you wanted an array.

I suggest you to use std::bitset instead
The value of r is actually calculated using
int r = ceil (log10 ((Emax - Emin)*pow(10, 4))/log10 (2));

I have never used bitset before. Can you show me an example. Great thanks.
It must be known at compile time. (¿is that a problem?)

http://cplusplus.com/reference/bitset/bitset/
std::bitset<16> bin(number); here we use a representation of 16 bits (the size must be known at compile time).
To access individual bits you could use operator[] by instance
1
2
3
4
for( int K=0; K<father.size()/2; ++K)
   child[K] = father[K];
for( int K=mother.size()/2; K<mother.size(); ++K)
   child[K] = mother[K];
Last edited on
The length is actually a variable depending on the range of E. Is there anyway I can do it without bitset?
But there is a limit, so you could simply ignore the `0' bits at the beginning. you could use another variable that holds the real length.

You could try std::vector for a variable-length array
1
2
3
4
5
6
std::vector<bool> dec2bin (float dec, int mod_type){
//...
   std::vector<bool> bin(r); //r elements (it can be variable)
//...
   return bin;
}
Last edited on
Topic archived. No new replies allowed.