It is giving that error message because you are attempting to assign the value of an int-valued expression to a byte
. That is a potentially lossy operation: intuitively, you cannot put all possible int
values into a byte
.
The Java language requires you to use a (byte)
cast when you assign an int-valued expression to a byte
.
There are two places where you are doing this:
cryptedByte[i] = (data[i] + 13) % 256;
decryptedByte[i] = (data[i] * 256) - 13;
In the first one, the value of the expression is in the range 0 to 255 ... but Java byte
values are in the range -128 to +127.
In the second one, the expression values potentially have values in the range (-128 * 256) - 13
to `(+127 * 256) - 13. That clearly won't fit.
But that is actually moot. The Java does not allow variants of the above code even if you (a smart human being) can prove that the range of the expression would "fit" into a byte
. The JLS forbids this. (A Java compiler not required to be a general theorem prover!!)
The only situation where an int-valued expression can be assigned to a byte
without a type-cast is when the expression is a compile-time constant expression AND the actual value of the expression is in the range of byte
.
If you are interested, this is specified in JLS 15.2 Assignment Contexts which states:
In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:
- A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
(You need to chase down what the spec means by "constant expression" and "narrowing primitive conversion". I'll leave that for interested people to do for themselves.)
so would i add a (byte) cast in front of the 13 and 256?
Nope. You need to cast the entire expression; e.g.
cryptedByte[i] = (byte) ((data[i] + 13) % 256);