What are the equivalents of Swifts integer “Overfl

2019-07-30 02:15发布

问题:

Swift offers so called "Overflow Operators" &*, *+, &- for integer arithmetics (Swift Advanced Operators). They are designed to truncate the number of available bits when performing an operation that would lead to an overflow. For example:

var unsignedOverflow = UInt8.max // --> 255
unsignedOverflow = unsignedOverflow &+ 1 // --> 0, instead of overflow

Since Java doesn't support unsigned integers, there is probably not a real equivalent. In Java 8, there are functions like Integer.toUnsignedLong(int) or Integer.divideUnsigned(...) (Java 8 Class Integer) but unfortunately I cannot use this version of Java.

Is there some (easy) way to mimic the above behavior?

Edit: What I am trying to achieve is multiply and add positive integer values in Java so that the result is always a positive integer value. I tried using the % operator, but it returns the remainder, which can be a negative number.