Java error: possible loss of accuracy

I am making a small Java program that encrypts files of any type. The way I do this is this: I open the input file, read it in a byte array with the same size as this file, then do the encoding and write the entire array to a .dat file called output. Dat To index an array of bytes, I use a variable of type int. Code:

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

'arr' is an array of bytes with the same size as the input file.

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

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

(arrows on the operator ^)

required: byte

found: int

What happened? could you help me?

+6
source share
4 answers

The result of byte ^ byte is, intuitively, intuitively. Use the result coercion of the result of an expression when it returns to arr[i] :

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

This is due to the fact that the operator is defined as performing binary numeric advertising on its operands, and therefore what it does (in this case):

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

... which naturally leads to int . That's why we need to push back.

+7
source

The operands of ^ operators are first converted to int (this is called binary digital advertising). Thus, both byte ( arr[i-1] and arr[i] ) are converted to int , and the result of the operation is also int .

You need to return the result back to byte in order to assign it to arr[i] .

+1
source

If arr [] is of type byte [] , then the problem is when java performs any binary operation with integers, returns wither int or long depending on the operators. In this case, the result arr [i-1] ^ arr [i] is the int that you are trying to store in the byte .

0
source

Take a look at JLS 15.22.1

When both operands of the operator &, or, or | have a type that is convertible (Β§ 5.1.8), to a primitive integral type , binary numeric promotion is first performed on operands (Β§5.6.2).

And JLS 5.6.2

1. If any operand has a reference type, it undergoes unpacking of the transformation (section 5.1.8).

2. Conversion of a primitive primitive (Β§5.1.2) is used to convert one or both operands, as specified in the following rules:

  • If one of the operands is of type double, the other is converted to double.

  • Otherwise, if either operand is of type float, the other is converted to float.

  • Otherwise, if either operand is of type long, the other is converted to long.

  • Otherwise, both operands are converted to int type.

Therefore, the expression below is first converted to int .

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

To return it back to byte , use an explicit expression:

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

Source: https://habr.com/ru/post/949541/


All Articles