java - I add two numbers with the same way but get different values -
the following code , extremely confused results get.
byte[] bytes = new byte[2]; bytes[0] = (byte)0xe6; bytes[1] = (byte)0x1b; int high = (bytes[1] & 0xff)*256; int low = bytes[0] & 0xff; double j = high + low; double = (bytes[1] & 0xff)*256 + bytes[0] & 0xff; system.out.println(bytes[1] & 0xff); system.out.println(bytes[0] & 0xff); system.out.println((bytes[1] & 0xff)*256); system.out.println(i); system.out.println(j);
logically, i
, j
same result quite amazing.
results:
27 230 6912 230.0 7142.0
i
, j
should same isn't. don't know reason. there explanation this?
they aren't equivalent; in java, the bitwise &
operator has lower precedence +
operator. i
being defined ((bytes[1] & 0xff)*256 + bytes[0])& 0xff
, evaluates 230, instead of intended 7142. replacing line i = (bytes[1] & 0xff)*256 + (bytes[0] & 0xff);
need do.
Comments
Post a Comment