How can I invert bits of an unsigned byte in Java?

DavidKelly999 picture DavidKelly999 · Jul 24, 2010 · Viewed 39k times · Source

I am trying to write a decoder for a very simple type of encryption. Numbers from 0-255 are entered via Scanner, the bits are inverted, and then converted to a character and printed.

For example, the number 178 should convert to the letter "M".

178 is 10110010.

Inverting all of the bits should give 01001101, which is 77 or "M" as a character.

The main problem I have is that, as far as I can tell, Java does not support unsigned bytes. I could read values as an int or a short, but then the values will be off during the conversion due to the extra bits. Ideally I could just use the bitwise complement operator, but I think I will end up getting negative values if I do this with signed numbers. Any ideas on how I should approach this?

Answer

stacker picture stacker · Jul 24, 2010

I would simply use the ones complement and get rid of the other bits by using binary and.

public class Conv {
    public static void main(String[] args) {
        int val = 178;
        val = ~val & 0xff;
        System.out.println((char) val);
    }
}