Search code examples
javabinarybytenumberformatexception

Parse signed Byte from binary | Java


I have the following problem in Java. I am using an encryption algorithm that can produce negative bytes as outcome, and for my purposes I must be able to deal with them in binary. For negative bytes, the first or most significant bit in the of the 8 is 1. When I am trying to convert binary strings back to bytes later on, I am getting a NumberFormatException because my byte is too long. Can I tell Java to treat it like an unsigned byte and end up with negative bytes? My code so far is this:

private static String intToBinByte(int in) {
        StringBuilder sb = new StringBuilder();
        sb.append("00000000");
        sb.append(Integer.toBinaryString(in));
        return sb.substring(sb.length() - 8);
}
intToBinByte(-92); // --> 10100100
Byte.parseByte("10100100", 2) // --> NumberFormatException
Value out of range. Value:"10100100" Radix:2

Is there a better way to parse signed Bytes from binary in Java? Thanks in advance!


Solution

  • I have written the following function to solve the problem:

    private static byte binStringToByte(String in) {
        byte ret = Byte.parseByte(in.substring(1), 2);
        ret -= (in.charAt(0) - '0') * 128;
        return ret;
    }