在android上将Hex转换为Binary

时间:2013-05-24 09:17:51

标签: android binary hex

我使用此代码将十六进制转换为二进制,但仅适用于8位。如何扩展到16位?例如,我想将FFFF转换为1111111111111111 ....我还需要填零0 ...

 void HexToBinary1(String Hex) {

    int i = Integer.parseInt(Hex, 16);//16 bits
    String Bin = Integer.toBinaryString(i);//Converts int to binary

    String Bin2="";
    if(Bin.length()==8){Bin2=Bin;}
    if(Bin.length()==7){Bin2="0"+Bin;}
    if(Bin.length()==6){Bin2="00"+Bin;}
    if(Bin.length()==5){Bin2="000"+Bin;}
    if(Bin.length()==4){Bin2="0000"+Bin;}
    if(Bin.length()==3){Bin2="00000"+Bin;}
    if(Bin.length()==2){Bin2="000000"+Bin;}
    if(Bin.length()==1){Bin2="0000000"+Bin;}

    text1.setText(Bin2);//Shows binary
}

3 个答案:

答案 0 :(得分:1)

使用

String HexToBinary(String Hex) {
        String bin =  new BigInteger(Hex, 16).toString(2);
        int inb = Integer.parseInt(bin);
        bin = String.format(Locale.getDefault(),"%08d", inb);
        return bin;
}

它将二进制字符串返回为8位格式。

答案 1 :(得分:1)

你需要告诉Java int是十六进制的,如下所示:

String HexToBinary(String Hex) {
    int i = Integer.parseInt(Hex, 16);
    String Bin = Integer.toBinaryString(i);
    return Bin;
}

答案 2 :(得分:0)

试试这个

public static String getBits(double value)
{
    //get bit-string of double
    String printString = (Long.toBinaryString(Double.doubleToRawLongBits(value)));

    //add leading zeros if bitstring is shorter than 64 bits
    while (printString.length() < 64)
        printString = "0" + printString;

    //format string by adding byte padding
    StringBuilder bitwise = new StringBuilder();
    for(int i = 0; i<8; i++)
        bitwise.append(printString.substring(i*8, (i+1)*8)+" ");

    return bitwise.toString();
}

随意进一步适应整数并添加解析HEX字符串的功能。