Java中的双重比较技巧 [英] Double comparison trick in Java

查看:60
本文介绍了Java中的双重比较技巧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++允许您将两个整数比较组合在一起进行范围检查,例如

 (unsigned)X< (无符号)上部



<时返回true pre> 0< = X<上层

Java语言没有未签名的类型。您是否看到一种方法,可以通过一次比较并获得不太多的开销?



更新



根据@Bathsheba的评论,char类型为无符号16位,将适合我的目的,因为我的整数实际上在短裤范围内。



问题仍然存在,对于普通的 int s。



可能在一行中(X |(Upper-1-X))的> = 0 ,它允许30位的范围。

解决方案

如果您希望Java中的数据类型能够保存无符号32位int可以容纳的值的范围,那么您需要 long 。您可以用32个位进行位掩码,将可能为负的有符号整数转换为肯定为 long 的值。

 (x& 0xffffffffL)< upper 

// ^
//隐式转换为long(两个参数)

当然,64位的与和64位的比较将花费一些额外的时间,但可能少于管道中断。


C++ allows you to combine two integer comparisons in one for range checking, like

(unsigned)X < (unsigned)Upper

which returns true when

0 <= X < Upper

The Java language has no unsigned type. Do you see a way to obtain the same effect, using a single comparison and not too much overhead ?

Update:

From a comment by @Bathsheba, the char type is unsigned 16 bits and will be fit for my purpose, as my integers are actually in the range of shorts.

The question remains open for plain ints.

Possibly something in the line of (X | (Upper - 1 - X)) >= 0, which allows a range of 30 bits.

解决方案

If you want a datatype in Java that is able to hold the range of values that an unsigned 32-bit int can hold, then you need long. You can bit-mask with 32 one-bits to convert the signed int that is possibly negative to a surely-positive long value.

(x & 0xffffffffL) < upper

//             ^
//             Implicit conversion to long (of both arguments)

Of course the 64-bit "and" and the 64-bit comparison will take some extra time but probably less than the pipe line breaks.

这篇关于Java中的双重比较技巧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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