初学者数字转换程序(二进制到数字,十六进制到数字)Java实现问题

时间:2018-09-28 00:21:37

标签: java type-conversion

以下函数用于将十六进制字符串和二进制字符串转换为其数字形式。我不确定如何在hexStringDecode方法内实现第三个方法(hexCharDecode)。我希望有人可以帮助解释如何包含此内容,并且它比我已经为hexStringDecode定义的方法更有效吗?

谢谢可爱的人!

 //method to identify and filter out the "0x" if it is provided using an if-else and to decode the hexadecimal

public static long hexStringDecode(String hex) {
    if (hex.charAt(0) == '0' && hex.charAt(1) == 'x') {
        return Long.parseLong(hex.substring(2), 16);
    } else {
        return Long.parseLong(hex, 16);
    }
}

public static short hexCharDecode(char digit) {
    String s = digit + "";
    return Short.parseShort(s, 16);
}

    //method to identify and filter out the "0b" if it is provided using an if-else and to decode the binary

public static short binaryStringDecode(String binary) {
    if (binary.charAt(0) == '0' && binary.charAt(1) == 'b') {
        return Short.parseShort(binary.substring(2), 2);
    } else {
        return Short.parseShort(binary, 2);
    }
}

    //method to convert binary to hex
public static String binaryToHex(String binary) {
    short s = binaryStringDecode(binary);
    return Integer.toHexString(s).toUpperCase();
}

强文本

0 个答案:

没有答案