core - Arithmatic Operation in Java -
assume have 1 arithmetic function add 2 long variables , return long value. if pass long.maxvalue() argument wont give perfect result. solution that? code below explains mean:
public class arithmaticexample { public static void main(string[] args) { system.out.println(arithmaticexample.addlong(long.max_value, long.max_value)); } public static long addlong(long a,long b){ return a+b; } }
so can see wood trees, let's recast problem using byte rather long , consider
byte = 0b01111111; // i.e. 127, largest value of `byte`. byte b = 0b01111111; byte c = (byte)(a + b); where need explicit cast circumvent conversion of a + b int.
computing c hand gives 0b11111110. is, of course, bitwise representation of -2 in 8 bit 2's complement type.
so answer byte case -2. , same holds true long: there more 1 bits contend in addition.
note although well-defined in java, same cannot said c , c++.
if need add 2 long values of such magnitude consider using biginteger.
Comments
Post a Comment