Java:Bytes转short、int、long


Java:Bytes转short、int、long

bytes转short、int、long

/**
  * @description bytes转short
  */
public static short bytesToShort(byte[] b) {  
    short s = 0;  
    short s0 = (short) (b[0] & 0xff);// 最低位  
    short s1 = (short) (b[1] & 0xff);  
    s0 <<= 8;
    s = (short) (s0 | s1);  
    return s;  
}
/** * @description bytes转int */ public static int byteArrayToInt_2(byte[] b) { return b[1] & 0xFF | (b[0] & 0xFF) << 8; } /** * @description bytes转int */ public static int byteArrayToInt(byte[] b) { return b[3] & 0xFF | (b[2] & 0xFF) << 8 | (b[1] & 0xFF) << 16 | (b[0] & 0xFF) << 24; } /** * @description bytes转long */ public static long byteArrayToLongL(byte[] b) {   return b[3] & 0xFFL |    (b[2] & 0xFFL) << 8| (b[1] & 0xFFL) << 16 | (b[0] & 0xFFL) << 24 ; }

/**
  * @description bytes转long
  */
public static long byteArrayToLong8(byte[] b) {
return (long)b[9] & 0xFF |
(long)(b[8] & 0xFF) << 8|
(long)(b[7] & 0xFF) << 16 |
(long)(b[6] & 0xFF) << 24 |
(long)(b[5] & 0xFF) << 32|
(long)(b[4] & 0xFF) << 40|
(long)(b[3] & 0xFF) << 48 |
(long)(b[2] & 0xFF) << 56 ;
}

short、int、long转bytes

// long转为4位byte数组
public static byte[] longToByteArrLen4(long x) {  
    return new byte[] {   
        (byte) ((x >> 24) & 0xFF),   
        (byte) ((x >> 16) & 0xFF),      
        (byte) ((x >> 8) & 0xFF),      
        (byte) (x & 0xFF)   
    };     
}    
// int类型转换为长度2的byte数组
public static byte[] intToByteArray_2(int a) {   
    return new byte[] {        
        (byte) ((a >> 8) & 0xFF),      
        (byte) (a & 0xFF)   
    };   
} 
//int类型转换为长度4的byte数组
public static byte[] intToByteArray(int a) {   
    return new byte[] {   
        (byte) ((a >> 24) & 0xFF),   
        (byte) ((a >> 16) & 0xFF),      
        (byte) ((a >> 8) & 0xFF),      
        (byte) (a & 0xFF)   
    }; 
}
//short类型转换长度1的byte
public static byte shortToByte(short x) {
    byte b = (byte) (0x00FF & x);
    return b;
}
//int类型转1位byte
public static byte intToByte(int a) {   
    return  (byte) (a & 0xFF);
}