【问题标题】:converting binary/decimal fraction to hexadecimal in java -unexpected output在java中将二进制/十进制小数转换为十六进制 - 意外输出
【发布时间】:2014-09-30 05:42:55
【问题描述】:

我正在尝试编写一个程序,将二进制(带或不带小数)输入转换为几乎完成的十六进制,但不幸的是在十六进制输出中缺少点 (".")。

假设我的预期输出是 e7.6 ,但我得到的是 e76

只有"." 丢失了。

这是我的 BinToHex 类..

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);
    }   
}       

我的主要测试类..

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

我被困住了! 请帮忙。

【问题讨论】:

  • 好吧-我必须承认...我完全被你的代码弄糊涂了^^完全^^你能不能把那个代码分成更多的方法来指出你做了什么?或者也许你提供一些 cmets 来解释你在这个或那个代码块中做了什么?我真的不想冒犯你,但即使读了两三次我也没有明白^^还有一点是这个问题有很多访客但没有人敢回答,可能是因为上面的原因 - 没有冒犯,真的!!
  • 问题是 decimalOfInput 初始化器给它一个整数除以 8 的值。将其乘以 16 得到一个整数,因此不输入句点的测试成功。我无法告诉您如何解决它,因为就像@MartinFrank 一样,我不知道您要做什么。
  • 好的,我告诉你出了什么问题^^ if (tempDec == (int)tempDec) 将被联系到!当它到达时,你打电话给break;,当这种情况发生时你永远不会到达代码hexOutput = hex + "."; ...所以我猜你只是删除了break-statement ...但这只是一个幸运的猜测...... . 如果我是你,我会尝试拆分字符串并使用Integer.parseInt(str, 16);(十六进制输入)或Integer.parseInt(str, 2);(二进制输入)作为点前后的字符串......
  • 为了使用 parseInt 策略,该点后面的字符串需要添加尾随零以使其长度为 4 的倍数。如果将 Integer.parseInt(str, 2) 应用于“011”,结果将是3,而不是 6。
  • 好的,你用的是什么底座?你能提供它你正在使用32位表示吗?还是8位?不要隐瞒它^^

标签: java debugging binary hex


【解决方案1】:

真的,不是我忍不住要写一个解决方案...在拥有这么长的 cmets 之后,我只需要几分钟 ^^

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;
}

【讨论】:

  • Thnx,但我认为如果二进制输入的小数部分超过四位,这将不起作用。而对于 cmets,可能你没有正确阅读我的代码,我的代码中也有 cmets,你以某种方式错过了它。@MartinFrank
  • 是的……我猜你是对的……对不起,我误解了你……抱歉给你添麻烦了……
【解决方案2】:

终于找到了一种将十进制(带或不带小数)转换为十六进制的合适算法。

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

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);    

    }
}

【讨论】:

    猜你喜欢
    • 2012-06-26
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 2012-04-08
    • 2014-10-30
    • 2016-08-28
    相关资源
    最近更新 更多