xaxb
V2EX  ›  Java

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

  •  
  •   xaxb · Mar 22, 2019 · 3832 views
    This topic created in 2800 days ago, the information mentioned may be changed or developed.
    private boolean test(long ip) {
            return ip > 0x1000000 && ip < 0xff000000;
        }
    
    10 replies  •  2019-03-23 15:01:09 +08:00
    rookiewhy
    rookiewhy
    Mar 22, 2019
    1
    想问下 为啥前面的是 7 位后面的是 8 位?
    xaxb
    xaxb
    OP
    Mar 22, 2019
    2
    对应 ip 地址的第一个字段,找到原因了 LongCache 引起的
    falsemask
    falsemask
    Mar 22, 2019
    3
    @sunweiqiang8 是 cache 原因吗 0x1000000 = 16777216,0xff000000=-16777216,大于大,小于小,一直返回 false 正常的吧
    xaxb
    xaxb
    OP
    Mar 22, 2019
    4
    @falsemask 类型是 long, 0xff000000=37700000000
    解决了
    ```java
    private boolean test(long ip) {
    return Long.compare(ip, 0x1000000) == 1 && Long.compare(ip, 0xff000000) == -1;
    }
    ```
    xaxb
    xaxb
    OP
    Mar 22, 2019
    5
    @falsemask
    打错了 0xff000000 = 4278190080
    xaxb
    xaxb
    OP
    Mar 22, 2019
    6
    ip < 0xff000000
    更改为
    Long.compareUnsigned(ip, 0xff000000) == -1

    编译器把 0xff000000 识别为 int 类型了,变成了负数
    felixlong
    felixlong
    Mar 22, 2019 via Android
    7
    改成 0xff000000L 不就行了吗?搞这么复杂。
    bxb100
    bxb100
    Mar 22, 2019
    8
    @felixlong bingo
    msg7086
    msg7086
    Mar 23, 2019
    9
    @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
    Citrus
    Mar 23, 2019
    10
    @felixlong 是啊,看的我一愣一愣的,折腾这么长干嘛。。。
    @sunweiqiang8 建议使用 IDE 写代码,像 IDEA 会提示这段代码有问题,直接识别出 ip > 0x1000000 && ip < 0xff000000 always false
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2052 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 04:09 · PVG 12:09 · LAX 20:09 · JFK 23:09
    ♥ Do have faith in what you're doing.