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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With