-2

How to convert float number like -2.25 to binary? I need creating a population for a genetic algorithm with domain from -20.5 to 20.5 . Each chromosomes should be represinted with 0s and 1s only

1 = 01
0 = 00
4 = 100

and so on

I know how to convert the "2" but not the 0.25 nor the number with negative sign

this is my method and I'm stuck there. I could not know how to enhance it to give me the correct result when converting float, negative int or negative float number

public class MinimizeRastriginFunction {

    public static String binary="";

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        //float x=(float) 2.5;
        int x =5 ;
        System.out.println("Before :" + x);
        decToBin(x);
        System.out.println("After :"  + binary);


    }

    private static Object decToBin(int dec) {
        // TODO Auto-generated method stub
        int num;

        if (dec <=1) {
            binary +=dec;
            return null;   // KICK OUT OF THE RECURSION
        }

        num= dec %2; 
        decToBin(dec >>1);
        binary += num;
        return null;    
    }
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
Muneerah Rashed
  • 313
  • 3
  • 13
  • Start with [`Float.floatToRawIntBits`](https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#floatToRawIntBits(float)). Then there are various ways of converting an `int` to a `byte[]`. Or you could `Integer.toBinaryString`. – Boris the Spider Nov 11 '17 at 12:49
  • 1
    Also, [mandatory link](http://floating-point-gui.de/formats/fp/). – Boris the Spider Nov 11 '17 at 12:55
  • 1
    I'd recommend to remove the misleading "genetic-algorithm" and "genetic-programming" tags. – Ralf Kleberhoff Nov 11 '17 at 12:55
  • 1
    Technically, `Float.parseFloat()` does exactly what you gave us as the question. It takes a string with a decimal representation of a fractional (floating point) number, e.g. "-2.25" and returns a `float`: a machine-oriented binary floating point representation. But I guess you want to see some readable string representation like "-10.01". Correct? And maybe you want to do it "yourself", not relying on some library. – Ralf Kleberhoff Nov 11 '17 at 13:03
  • Integer part is made of sum of positive powers of 2, and then decimal part is made of sum of negative powers of 2. So proceed by multiplying by 2 instead of dividing. 0.25*2=0.5 (retain 0), 0.5*2=1 (retain 1) then stop, so 0.25 is 0.01 in binary representation. – Jean-Baptiste Yunès Nov 11 '17 at 13:31
  • It is not quite clear how you would map values to bits. Could you give an example of how you would map a few values like -20.5, -19.7, +3.0, etc. etc. to bits? – Rudy Velthuis Nov 12 '17 at 00:12

2 Answers2

0

UPDATE as per your comment, keep only 20 charachters then the solution would look like this:

import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(convert("0.25"));
        System.out.println(convert("-0.25"));
        System.out.println(convert("2"));
        System.out.println(convert("-2"));
    }
    public static String convert(String input) {
        double number = Double.parseDouble(input);
        long longBits = Double.doubleToLongBits(number);
        String result = Long.toBinaryString(longBits);

        String upToNCharacters = result.substring(0, Math.min(result.length(), 20));
        return upToNCharacters;
    }
}

which outputs:

11111111010000000000
10111111110100000000
10000000000000000000
11000000000000000000

why don't you try this approach. There is an inbuilt function that can help you

for example:

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(convert("0.25"));
        System.out.println(convert("-0.25"));

    }

    public static String convert(String input) {

        double number = Double.parseDouble(input);
        long longBits = Double.doubleToLongBits(number);
        String result = Long.toBinaryString(longBits);

        return result.replaceAll("0+$", "");;
    }

}

check also here

You can use it to convert everything you like dec, fload, negative dec/float(s)

System.out.println(convert("0.25"));
System.out.println(convert("-0.25"));
System.out.println(convert("2"));
System.out.println(convert("-2"));

Output would be:

11111111010000000000000000000000000000000000000000000000000000
1011111111010000000000000000000000000000000000000000000000000000
100000000000000000000000000000000000000000000000000000000000000
1100000000000000000000000000000000000000000000000000000000000000

and to have some format in your output just do this (using regex to remove all trailing 0s):

return result.replaceAll("0+$", "");

and the output will be the one you desire

1111111101
101111111101
1
11

And finally if you need to return an array of Int (vector), or something else you can process them one by one by something like this mentioned here. mmoore has provided a splendid answer for the conversion in a simple loop :)

oetoni
  • 3,269
  • 5
  • 20
  • 35
0

I suppose you don't need infinite resolution for your numbers, e.g. 2.4999 need not get a different bit pattern than 2.5000.

With a resolution if e.g. 0.01 you can do: int bitsNumber = (int) ((value + 20.5) / 0.01); and then convert the int to the binary string the way you already did it (or with Integer.toBinaryString(bitsNumber) ).

Ralf Kleberhoff
  • 6,990
  • 1
  • 13
  • 7