byte[]和int相互轉換備份

import java.nio.ByteOrder;

/**
 */
public class AnyIdUtil {
    public final static boolean IS_BIG_ENEIAN = (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN);

    public static byte[] int2bytes(int value) {
        byte[] bytes = new byte[4];
        if (!IS_BIG_ENEIAN) { // 小端
            bytes[3] = (byte) ((value >> 24) & 0xFF);
            bytes[2] = (byte) ((value >> 16) & 0xFF);
            bytes[1] = (byte) ((value >> 8) & 0xFF);
            bytes[0] = (byte) (value & 0xFF);//byte[0] 存儲 數據高位
        } else {//大端
            bytes[0] = (byte) ((value >> 24) & 0xFF); //byte[0] 存儲數據高位
            bytes[1] = (byte) ((value >> 16) & 0xFF);
            bytes[2] = (byte) ((value >> 8) & 0xFF);
            bytes[3] = (byte) (value & 0xFF);
        }
        return bytes;
    }

    public static int bytes2int(byte[] bytes) {
        int value = 0;
        if (!IS_BIG_ENEIAN) {
            value = (int) ((bytes[0] & 0xFF)
                    | ((bytes[1] & 0xFF) << 8)
                    | ((bytes[2] & 0xFF) << 16)
                    | ((bytes[3] & 0xFF) << 24));
        } else {
            value = (int) (((bytes[0] & 0xFF) << 24)
                    | ((bytes[1] & 0xFF) << 16)
                    | ((bytes[2] & 0xFF) << 8)
                    | (bytes[3] & 0xFF));
        }
        return value;
    }


}

這個更好理解:java

  1.  public static int byte4ToInt(byte[] bytes, int off) {  
  2.         int b0 = bytes[off] & 0xFF;  
  3.         int b1 = bytes[off + 1] & 0xFF;  
  4.         int b2 = bytes[off + 2] & 0xFF;  
  5.         int b3 = bytes[off + 3] & 0xFF;  
  6.         return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;  
  7.     }  
相關文章
相關標籤/搜索