位到字节的字符串。值超出范围 - 转换错误java

时间:2016-04-12 11:56:38

标签: byte bit outofrangeexception

我需要转换通过String表示的位集。我的字符串是8的倍数,所以我可以将它除以8并得到内部有8位的子字符串。然后我必须将这些子字符串转换为字节并以HEX格式打印。例如:

String seq = "0100000010000110";

seq 要长得多,但这不是主题。您可以在下面看到 seq 中的两个子字符串。其中一个我遇到了麻烦,为什么?

        String s_ok = "01000000"; //this value is OK to convert
        String s_error = "10000110"; //this is not OK to convert but in HEX it is 86 in DEC 134

    byte nByte = Byte.parseByte(s_ok, 2);
    System.out.println(nByte);
    try {
        byte bByte = Byte.parseByte(s_error, 2);
        System.out.println(bByte);
    } catch (Exception e) {
        System.out.println(e); //Value out of range. Value:"10000110" Radix:2
    }
     int in=Integer.parseInt(s_error, 2);
     System.out.println("s_error set of bits in DEC - "+in + " and now in HEX - "+Integer.toHexString((byte)in)); //s_error set of bits in DEC - 134 and now in HEX - ffffff86

我无法理解为什么会出现错误,对于计算器来说,转换 10000110 不是问题。所以,我尝试了整数并且有 ffffff86 而不是简单的 86

请帮忙:为什么?以及如何避免这个问题。

1 个答案:

答案 0 :(得分:0)

好吧,我找到了如何避免 ffffff

System.out.println("s_error set of bits in DEC - "+in + " and now in HEX - "+Integer.toHexString((byte)in & 0xFF));

0xFF 已添加。不好的是 - 我仍然不知道那些 ffffff 来自哪里,我不清楚,我做了什么。它是某种字节乘法还是掩盖?我输了。