0

I am trying to write a program that converts binary(with or without fraction) inputs into hex which is nearly done but unfortunately in the hex output the point (".")is missing.

Suppose my expected output is e7.6 , but i am getting e76 instead.

only the "." is missing.

here is my BinToHex class..

import java.io.*;

//tried to convert the binary into dec and then dec to hex
public class BinToHex {
    double tempDec,fractionpart;
    long longofintpart,templongDec;
    String inpu ="11100111.011";
    String hexOutput=null,tempDecString,hex = null;

    static int i = 1;

    public void convertbintohex() {

            if (inpu.contains(".")) {

                int placesAfterPoint = inpu.length() - inpu.indexOf(".") - 1;//every thing
                long numerator = Long.parseLong(inpu.replace(".", ""), 2);//goes 
                double decimalOfInput = ((double) numerator) / (1L << placesAfterPoint);//alright  till here 


                while (true) {
                    tempDec = decimalOfInput * 16;
                    if (tempDec == (int)tempDec) {
                        tempDecString = String.valueOf((long)tempDec);
                        templongDec = Long.parseLong(tempDecString, 10);
                        hexOutput = Long.toHexString(templongDec);

                        break;
                    } else {
                        longofintpart  = (long)tempDec;
                        hex=Long.toHexString(longofintpart);
                        if(i==1){
                            hexOutput = hex + ".";
                            i=i+1;
                        }else{
                            hexOutput = hexOutput + hex;
                        }
                        fractionpart = tempDec-(int)tempDec;
                        decimalOfInput = fractionpart;
                    }
                }
            } else {
                    // this part is ok
                tempDecString = String.valueOf(Integer.parseInt(inpu, 2));
                templongDec = Long.parseLong(tempDecString, 10);
                hexOutput = Long.toHexString(templongDec);
            }
            System.out.println(hexOutput);
    }   
}       

my main Test class..

public class Test{
    public static void main(String args[]){
        BinToHex i = new BinToHex();
        i.convertbintohex();    
    }
}

I am stuck! plz help .

Cœur
  • 37,241
  • 25
  • 195
  • 267
Tiash
  • 109
  • 3
  • 14
  • well - i must confess... i puzzeled by your code^^ totally^^ could you eventually split that code into some more methods to point out what you do? or maybe you provide some comments to explain what you do in this or that codeblock? i really don't want to offense you, but even after reading it twice and thrice i don't get it^^ another point is that this question had quite some visitors but NOONE dared to answer, maybe because the reason above - no offense, really!! – Martin Frank Sep 30 '14 at 06:29
  • The issue is that the `decimalOfInput` initializer gives it a value that is an integer divided by 8. Multiplying that by 16 results in an integer, so the test for not putting in a period succeeds. I cannot tell you what to do to fix it, because, like @MartinFrank, I don't know what you are trying to do. – Patricia Shanahan Sep 30 '14 at 13:03
  • ok, i tell you what goes wrong ^^ `if (tempDec == (int)tempDec)` will be reached! and when it's reached, you call `break;` when that happens you will never reach the code `hexOutput = hex + ".";` ... so i guess you have simply remove the `break`-statement... but that is just a lucky guess... if i were you i would try to split the string and use `Integer.parseInt(str, 16);`(hex input) or `Integer.parseInt(str, 2);` (binary input) for the string before and after the dot... – Martin Frank Sep 30 '14 at 13:13
  • In order to use the parseInt strategy, the string after the point needs to have trailing zeros added to make its length a multiple of 4. If you apply `Integer.parseInt(str, 2)` to "011" the result will be 3, not 6. – Patricia Shanahan Sep 30 '14 at 13:16
  • ok, what base are you using? could you provide it you are using 32bit represntation? or 8bit? don't make a secret out of it ^^ – Martin Frank Sep 30 '14 at 13:19
  • have you tried to remove the `break`-statement? – Martin Frank Sep 30 '14 at 13:26
  • if i remove the "break" statement then where will i end the while-loop? – Tiash Sep 30 '14 at 13:37

2 Answers2

1

really, not i can't resist to write a solution... after having such long comments, it jst takes me some minutes ^^

final int CODEBASE = 16;
String input = "11100111.011";

//lets see if we have a '.' in our String
if (input.indexOf(".") > 0) {

    //yes, we have one - so we can split the string by '.'
    String splits = input.split(".");

    //the part left of the dot
    String beforeDot = splits[0];

    //the part right of the dot
    String afterDot = splits[1];

    //it's a incomplete input, we must fill up with 
    //trailing zeros according to out code base
    afterDot.fillTrailingZeros(afterDot, CODEBASE);

    //now we can parse the input
    int asIntBefore = Integer.parseInt(beforeDots, 2);
    int asIntAfter = Integer.parseInt(afterDot , 2);

} else { 
    //use your working code for
    //input wthoput dot HERE
}

//fills trailing zeros to input String
String fillTrailingZeros(String input, int base){

    //as long as our String is shorter than the codebase...
    while (input.length() < base){

        //...we have to add trailing zeros
        input = input +"0";
    }
    return input;
}
Martin Frank
  • 3,445
  • 1
  • 27
  • 47
  • Thnx,but I don't think this will work if the binary input has more than four digits in its fraction part. and for comments,probably you haven't read my code properly ,there were comments in my code too, you missed it somehow.@MartinFrank – Tiash Sep 30 '14 at 16:50
  • Yeah... i guess you are right... sorry, that i misunderstood you... sorry for making any trouble... – Martin Frank Sep 30 '14 at 19:03
1

At last found a proper algorithm for converting decimal(with or without fraction) to hex.

besides, binary(with or without fraction) to decimal in Java is here

The algorithm for converting decimal(with or without fraction) into hex in Java

import java.math.*; 

public class DecimalToHex{
    public String decimalToHex(String decInpString){

        StringBuilder hexOut = new StringBuilder();
        double doubleOfDecInp = Double.parseDouble(decInpString);

        if(doubleOfDecInp < 0){

            hexOut = hexOut.append("-");
            doubleOfDecInp = -doubleOfDecInp;
        }

        BigInteger beforedot = new BigDecimal(doubleOfDecInp).toBigInteger();
        hexOut.append(beforedot.toString(16));

        BigDecimal bfd =new BigDecimal(beforedot);
        doubleOfDecInp = doubleOfDecInp - bfd.doubleValue();

        if(doubleOfDecInp == 0){
            return hexOut.toString();
        }
        hexOut.append(".");

        for (int i = 0; i < 16; ++i) {
            doubleOfDecInp = doubleOfDecInp * 16;
            int digit = (int)doubleOfDecInp;

            hexOut.append(Integer.toHexString(digit));

            doubleOfDecInp = doubleOfDecInp - digit;

            if (doubleOfDecInp == 0)
                break;
        }

        return hexOut.toString();
    }

    public static void main(String args[]){

        String decimalInp = "-0.767";
        String out ; 
        DecimalToHex i = new DecimalToHex();
        out = i.decimalToHex(decimalInp);
        System.out.println(out);    

    }
}
Community
  • 1
  • 1
Tiash
  • 109
  • 3
  • 14