V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
alex8
V2EX  ›  Java

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

  •  
  •   alex8 · 2019-03-22 16:33:32 +08:00 · 2409 次点击
    这是一个创建于 1852 天前的主题,其中的信息可能已经有所发展或是发生改变。
    private boolean test(long ip) {
            return ip > 0x1000000 && ip < 0xff000000;
        }
    
    10 条回复    2019-03-23 15:01:09 +08:00
    rookiewhy
        1
    rookiewhy  
       2019-03-22 16:42:25 +08:00
    想问下 为啥前面的是 7 位后面的是 8 位?
    alex8
        2
    alex8  
    OP
       2019-03-22 16:44:39 +08:00
    对应 ip 地址的第一个字段,找到原因了 LongCache 引起的
    falsemask
        3
    falsemask  
       2019-03-22 16:48:46 +08:00
    @sunweiqiang8 是 cache 原因吗 0x1000000 = 16777216,0xff000000=-16777216,大于大,小于小,一直返回 false 正常的吧
    alex8
        4
    alex8  
    OP
       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
        5
    alex8  
    OP
       2019-03-22 16:59:30 +08:00
    @falsemask
    打错了 0xff000000 = 4278190080
    alex8
        6
    alex8  
    OP
       2019-03-22 17:06:39 +08:00
    ip < 0xff000000
    更改为
    Long.compareUnsigned(ip, 0xff000000) == -1

    编译器把 0xff000000 识别为 int 类型了,变成了负数
    felixlong
        7
    felixlong  
       2019-03-22 18:45:56 +08:00 via Android
    改成 0xff000000L 不就行了吗?搞这么复杂。
    bxb100
        8
    bxb100  
       2019-03-22 19:22:15 +08:00
    @felixlong bingo
    msg7086
        9
    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
        10
    Citrus  
       2019-03-23 15:01:09 +08:00
    @felixlong 是啊,看的我一愣一愣的,折腾这么长干嘛。。。
    @sunweiqiang8 建议使用 IDE 写代码,像 IDEA 会提示这段代码有问题,直接识别出 ip > 0x1000000 && ip < 0xff000000 always false
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4003 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 10:28 · PVG 18:28 · LAX 03:28 · JFK 06:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.