20

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?

DavidKelly999
  • 301
  • 1
  • 2
  • 5

7 Answers7

17

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);
    }
}
stacker
  • 68,052
  • 28
  • 140
  • 210
12
~n & 0xff

~ does the complement and implicitly converts to an integer like all numeric operations do, then & 0xff masks out everything except the lower 8 bits to get the unsigned value, again as an integer.

I first read your question differently, to invert the order instead of the values of the bits, and this was the answer.

You can use Integer.reverse() (untested):

Integer.reverse(n << 24) & 0xff
starblue
  • 55,348
  • 14
  • 97
  • 151
  • 1
    If anybody is using this, the `Integer.reverse` method works perfectly (tested)! Thanks btw! – Squeazer Nov 08 '14 at 21:13
  • Link is broken, correct link is here for [Integer.reverse()](https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#reverse(int)) – Akshay Mahajan Apr 29 '20 at 15:20
6

Bitwise operations in Java are defined for int so it makes sense to work with int rather than byte. You can use Scanner.nextInt, rather than Scanner.nextByte. You should validate the user's input to ensure that all integers entered are in the range 0 to 255 and display an appropriate error message if an out-of-range number is encountered.

Once you have the number stored in an integer then to flip the least significant 8 bits you can XOR with 0xff. This should work as you expect for all inputs between 0 and 255:

x ^= 0xff;

Example:

String input = "178 0 255";
Scanner s = new Scanner(input);
while (s.hasNextInt()) {
    int x = s.nextInt();
    if (x < 0 || x > 255) {
        System.err.println("Not in range 0-255: " + x);
    } else {
        x ^= 0xff;
        System.out.println(x);
    }
}

Result:

77
255
0
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • This will not work if the value originally is stored in a byte, because then it will be sign-extended to a negative integer. – starblue Jul 24 '10 at 10:53
  • @starblue: It appears that he is using a Scanner. I've updated my answer to mention this. – Mark Byers Jul 24 '10 at 11:02
3

If Java supports this, you could read it into a larger type, bitwise-compliment, then bit-mask out the unwanted bits.

int x = [your byte];
x = ~x & 0xFF;
Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183
0

The easiest way to do this is three stages:

  1. Read the value as an int (32 bits in java). It may read as negative but we only care about the bottom 8 bits anyway. int i = scanner.nextByte();
  2. Do the inversion as an int using bitwise operators (as you say will give you 1s as high order bits: i = ~i;
  3. Lose the high order bits with a logical AND: i = i & 0xFF;

Then just use the result as a character (which is actually 16 bits in java, but we will only use 8 of them):

char c=(char)a;
System.out.println(c); 

All together:

int i = scanner.nextByte(); // change this to nextInt() depending on file format
i = ~i;
i = i & 0xFF;
char c=(char)a;
System.out.println(c); 
Nick Fortescue
  • 43,045
  • 26
  • 106
  • 134
-1

Here are Java bytes, sorted by binary representation (from 00000000 to 11111111):

0, 1, 2, .., 126, 127, -128, -127, .., -2, -1

00000000 is 0, 11111111 is -1

Inverted 0 is -1, inverted 1 is -2, ..., inverted 127 is -128. Thus if you want to invert bits of Java byte you should get your byte with opposite sign and subtract one:

byte myByte = 123;
byte myInvertedByte = -myByte-1;
Vlad
  • 1,631
  • 1
  • 16
  • 21
-2
private byte reverseBitsByte(byte x)
{
    int intSize = 8;

    byte y = 0;
    for (int position = intSize - 1; position >= 0; position--)
    {
        y += ((x & 1) << position);
        x >>= 1;
    }
    return y;
}
Xkynar
  • 935
  • 1
  • 10
  • 31