为什么我的Binary2Hex代码不起作用?

时间:2015-10-23 21:43:52

标签: java binary hex

我似乎无法在我的代码中找到问题。最终会出现编译错误。它说方法Binary2Hex将无限递归。我问TA,他说我输了一个字符串?我不明白

package binary2hex;

public class Binary2Hex {
public static String binary2Hex(String binary){
int pos = binary.length();
    String hex = "";
    while(pos>=0){
        int posMinus4 = pos-4;
        if(posMinus4<0)
            posMinus4 = 0;
        String last4Bits = binary.substring(posMinus4, pos);
        while(last4Bits.length()<4)
            last4Bits = "0" + last4Bits;
        switch(last4Bits){
            case"0000": hex = "0" + hex; break;
            case"0001": hex = "1" + hex; break;
            case"0010": hex = "2" + hex; break;
            case"0011": hex = "3" + hex; break;
            case"0100": hex = "4" + hex; break; 
            case"0101": hex = "5" + hex; break;
            case"0110": hex = "6" + hex; break;
            case"0111": hex = "7" + hex; break;
            case"1000": hex = "8" + hex; break;
            case"1001": hex = "9" + hex; break;
            case"1010": hex = "A" + hex; break;
            case"1011": hex = "B" + hex; break;
            case"1100": hex = "C" + hex; break;
            case"1101": hex = "D" + hex; break;
            case"1110": hex = "E" + hex; break;
            case"1111": hex = "F" + hex; break;    
        }
        pos -= 4;
    }
    return binary2Hex("1010");
}
public static void main(String[] args) {
    System.out.println( binary2Hex("1010101010111010"));

}

}

1 个答案:

答案 0 :(得分:0)

是的,你不应该进行递归,因为你在while循环中解决问题。你应该只返回十六进制。你在大多数情况下都得到了正确的代码。另外,另一个提示是,如果长度为0,则不应处理字符串。