Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java error: possible loss of precision

I'm making a small Java program which encrypts any type of file. The way I'm doing it, is the following: I open the input file, read it in a byte array with the same size as that file, then do the encoding, and write the whole array to a .dat file called output.dat. To index the byte array, I'm using a variable of type int. The code:

        for(int i : arr) {
            if(i>0) {
                arr[i] = arr[i-1]^arr[i];
            }
        }

'arr' is a byte array with the same size as the input file.

The error I get: CodingEvent.java:42: error: possible loss of precision

arr[i] = arr[i-1]^arr[i];

(an arrow spots on the ^ operator)

required: byte

found: int

What's wrong? Could you help me please?

like image 953
mpeter Avatar asked Jul 16 '13 09:07

mpeter


1 Answers

The result of byte ^ byte is, counter-intuitively, int. Use a cast on the result of the expression when assigning it back to arr[i]:

arr[i] = (byte)(arr[i-1]^arr[i]);

This is because the operator is defined as doing a binary numeric promotion on its operands, and so what it's really doing (in this case) is:

arr[i] = (int)arr[i-1]^(int)arr[i];

...which naturally results in int. Which is why we need the cast back.

like image 150
T.J. Crowder Avatar answered Sep 21 '22 12:09

T.J. Crowder