0

I need to convert the set of bits that are represented via String. My String is multiple of 8, so I can divide it by 8 and get sub-strings with 8 bits inside. Then I have to convert these sub-strings to byte and print it in HEX. For example:

String seq = "0100000010000110";

The seq is much longer, but this is not the topic. Below you can see two sub-strings from the seq. And with one of them I have trouble, why?

        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

I can't understand why there is an error, for calculator it is not a problem to convert 10000110. So, I tried Integer and there are ffffff86 instead of simple 86.

Please help with: Why? and how to avoid the issue.

Ajit Medhekar
  • 1,018
  • 1
  • 10
  • 39
Sergey Lotvin
  • 179
  • 1
  • 14

1 Answers1

0

Well, I found how to avoid ffffff:

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

0xFF was added. Bad thing is - I still don't know from where those ffffff came and I it is not clear for, what I've done. Is it some kind of byte multiplication or is it masking? I'm lost.

Sergey Lotvin
  • 179
  • 1
  • 14