### 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:

 ``12345678910111213141516`` `````` 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:
 ``123456789101112131415161718192021222324252627282930313233`` ``````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

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
 ``1234`` ``````for( int K=0; 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
 ``123456`` ``````std::vector dec2bin (float dec, int mod_type){ //... std::vector bin(r); //r elements (it can be variable) //... return bin; }``````
Last edited on
Topic archived. No new replies allowed.