0

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!

2 Answers 2

1

You can just parse it with a larger type, then cast it to byte. Casting simply truncates the number of bits:

byte b = (byte) Integer.parseInt("10100100", 2);
Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.