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

2019 年 3 月 22 日
 xaxb
private boolean test(long ip) {
        return ip > 0x1000000 && ip < 0xff000000;
    }
3650 次点击
所在节点    Java
10 条回复
rookiewhy
2019 年 3 月 22 日
想问下 为啥前面的是 7 位后面的是 8 位?
xaxb
2019 年 3 月 22 日
对应 ip 地址的第一个字段,找到原因了 LongCache 引起的
falsemask
2019 年 3 月 22 日
@sunweiqiang8 是 cache 原因吗 0x1000000 = 16777216,0xff000000=-16777216,大于大,小于小,一直返回 false 正常的吧
xaxb
2019 年 3 月 22 日
@falsemask 类型是 long, 0xff000000=37700000000
解决了
```java
private boolean test(long ip) {
return Long.compare(ip, 0x1000000) == 1 && Long.compare(ip, 0xff000000) == -1;
}
```
xaxb
2019 年 3 月 22 日
@falsemask
打错了 0xff000000 = 4278190080
xaxb
2019 年 3 月 22 日
ip < 0xff000000
更改为
Long.compareUnsigned(ip, 0xff000000) == -1

编译器把 0xff000000 识别为 int 类型了,变成了负数
felixlong
2019 年 3 月 22 日
改成 0xff000000L 不就行了吗?搞这么复杂。
bxb100
2019 年 3 月 22 日
@felixlong bingo
msg7086
2019 年 3 月 23 日
@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 年 3 月 23 日
@felixlong 是啊,看的我一愣一愣的,折腾这么长干嘛。。。
@sunweiqiang8 建议使用 IDE 写代码,像 IDEA 会提示这段代码有问题,直接识别出 ip > 0x1000000 && ip < 0xff000000 always false

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

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

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

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

© 2021 V2EX