这段代码为什么一直返回 false 呢{return ip > 0x1000000 && ip < 0xff000000;}

2019-03-22 16:33:32 +08:00
 alex8
private boolean test(long ip) {
        return ip > 0x1000000 && ip < 0xff000000;
    }
2418 次点击
所在节点    Java
10 条回复
rookiewhy
2019-03-22 16:42:25 +08:00
想问下 为啥前面的是 7 位后面的是 8 位?
alex8
2019-03-22 16:44:39 +08:00
对应 ip 地址的第一个字段,找到原因了 LongCache 引起的
falsemask
2019-03-22 16:48:46 +08:00
@sunweiqiang8 是 cache 原因吗 0x1000000 = 16777216,0xff000000=-16777216,大于大,小于小,一直返回 false 正常的吧
alex8
2019-03-22 16:57:32 +08:00
@falsemask 类型是 long, 0xff000000=37700000000
解决了
```java
private boolean test(long ip) {
return Long.compare(ip, 0x1000000) == 1 && Long.compare(ip, 0xff000000) == -1;
}
```
alex8
2019-03-22 16:59:30 +08:00
@falsemask
打错了 0xff000000 = 4278190080
alex8
2019-03-22 17:06:39 +08:00
ip < 0xff000000
更改为
Long.compareUnsigned(ip, 0xff000000) == -1

编译器把 0xff000000 识别为 int 类型了,变成了负数
felixlong
2019-03-22 18:45:56 +08:00
改成 0xff000000L 不就行了吗?搞这么复杂。
bxb100
2019-03-22 19:22:15 +08:00
@felixlong bingo
msg7086
2019-03-23 00:11:37 +08:00
@sunweiqiang8 不是编译器识别,是你这么输入就是 int 类型。

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int.

“ otherwise it is of type int ” —— 你没有输入 L,就意味着你明确指出这是一个 int 类型的数字。
Citrus
2019-03-23 15:01:09 +08:00
@felixlong 是啊,看的我一愣一愣的,折腾这么长干嘛。。。
@sunweiqiang8 建议使用 IDE 写代码,像 IDEA 会提示这段代码有问题,直接识别出 ip > 0x1000000 && ip < 0xff000000 always false

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/547468

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX