代码之家  ›  专栏  ›  技术社区  ›  Student

字节位置法

  •  0
  • Student  · 技术社区  · 16 年前

    在JDK或apachecommons(或其他jar)中有类似的东西吗?

    /**
     * Return the integer positive value of the byte. (e.g. -128 will return
     * 128; -127 will return 129; -126 will return 130...)
     */
    public static int toPositiveInt(byte b) {
    int intV = b;
     if (intV < 0) {
         intV = -intV;
         int diff = ((Byte.MAX_VALUE + 1) - intV) + 1;
         intV = Byte.MAX_VALUE + diff;
     }
     return intV;
        }
    
    1 回复  |  直到 16 年前
        1
  •  3
  •   Christian Semrau Louis Wasserman    16 年前

    通常,使用一些基本的位操作:

    public static int toPositiveInt(byte b) {
    return b & 0xFF;
    }
    

    因为它很短,所以通常是内联的,不作为方法调用。