The problem is in the first cast:
(byte) dana
dana
is converted to byte
, so then when it is later used in expression it needs to be widened back to int
and this is done with sign-extension. If number is negative all higher bits are set to 1 to keep its value in 2-complement.
Use bitmask instead:
short w = (short) ((dana & 0xff) << x);
Perhaps it would be even better to avoid using short
as well, since java does all arithmetics on int
anyway.