Swifts整数“溢出运算符"的等效项是什么? Java中的& *,& +和&-? [英] What are the equivalents of Swifts integer "Overflow Operators" &*, &+ and &- in Java?

查看:140
本文介绍了Swifts整数“溢出运算符"的等效项是什么? Java中的& *,& +和&-?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift为整数算术(

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

由于Java不支持无符号整数,因此可能没有真正的等价物.在Java 8中,有类似Integer.toUnsignedLong(int)Integer.divideUnsigned(...)(

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?

我要实现的目标是在Java中相乘并加上正整数值,以便结果始终是正整数值.我尝试使用%运算符,但它返回的余数可以是负数.

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.

推荐答案

Java没有未签名的数字.但是,您可以通过舍弃不需要的位来达到类似的结果:

Java does not have unsigned numbers. However, you may achieve a similar result by discarding the bits you do not want:

使用intlong,只要足以满足您的范围. 然后,对于每个操作,清除范围上方的位:

Use int or long, whichever is sufficient enough for your range. Then, for each operation, clear the bits above the range:

int abc = 255;
abc += 10;
abc &= 0xFF; // clears any bits other then least significant 8. 
System.out.println(abc); // --> 9

这篇关于Swifts整数“溢出运算符"的等效项是什么? Java中的& *,& +和&-?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆