Check carry from long operation in java -
i'm adding/subtrating numbers of type long. there way figure out if theoretical carry set operation?
this should do:
/** * add together 2 long's overflow detection (r = s + d) */ public static long add(final long s, final long d){ final long r = s + d; if (((s & d & ~r) | (~s & ~d & r)) < 0) throw new runtimeexception("long overflow add(" + s + ", " + d + ")"); homecoming r; }
this has been asked before here: how java handle integer underflows , overflows , how check it? (subtraction described there)
edit: since not clear if op meant unsigned addition, thats not hard detect. if 1 rethinks problem "if had 2 (unsigned) 64 bit values , add together them, bit 64 set in result (assuming bits numbered 0=lsb 63=msb in original operands)"
a little logical thinking leads conclusion bit 64 set if more 1 of next conditions true:
bit 63 of operand1 set bit 63 of operand2 set the sum of lower bits (0-62) of both operands produces carry bit 63thats reasonably easy check:
long operand1 = ... long operand2 = ... long bitmask = long.max_value; // bits 0-62 set, bit 63 clear int conditions = 0; if (operand1 < 0) ++conditions; if (operand2 < 0) ++conditions; if (((operand1 & bitmask) + (operand2 & bitmask)) < 0) ++conditions; if (conditions > 1) system.out.println("carry set!");
i havent spent time on thinking how optimized, i'm sure there more concise solution.
for unsigned subtraction pretty simple: borrow occurs in (a - b) if b greater a. can checked unsigned comparison, expressed in java as:
long flipsignbit = long.min_value; // bit 63 set, others clear if ((a ^ flipsignbit) < (b ^ flipsignbit)) system.out.println("borrow occurs");
java
No comments:
Post a Comment