What are the equivalents of Swifts integer “Overflow Operators” &*, &+ and &- in Java?

大憨熊 提交于 2019-12-24 08:49:26

问题


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.

来源:https://stackoverflow.com/questions/43029467/what-are-the-equivalents-of-swifts-integer-overflow-operators-and-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!