怎么进行数据类型转换?byte[] -> int

如何进行数据类型转换?byte[] - int关于android的数据类型强制转换的问题,我从文件里读取数据存在 byte[]

如何进行数据类型转换?byte[] -> int
关于android的数据类型强制转换的问题,我从文件里读取数据存在 byte[] b 的内存里。

有需要将4个字节转成 int,2个字节转成 short。

如果是c++,int i = *(int *)&b[0]; 即可。

Java应该如何做呢?

[解决办法]
int byteArrToInt(byte[] b, int off) {
       int value= 0;
       for (int i = 0; i < 4; i++) {
           int shift = (4 - 1 - i) * 8;
           value +=(b[i + off] & 0x000000FF) << shift;
       }
       return value;
 }
[解决办法]

ByteBuffer.wrap(null).getShort();

注意你的byte是big-end还是little-end
[解决办法]
/**
     * 获取byte数组的头两个字节对应的int值
     * @param bytes
     * @throws StringIndexOutOfBoundsException
     * @return
     */
    public static int byteArray2int(byte[] byteArray) throws StringIndexOutOfBoundsException {
        int num = byteArray[0] & 0xFF;  
        num 
[解决办法]
= ((byteArray[1] << 8) & 0xFF00);  
        return num;  
    }
    
    /**
     * 获取byte数组的头四个字节对应的int值(适用于低位在前,高位在后)
     * @param bytes
     * @throws StringIndexOutOfBoundsException
     * @return
     */
    public static int byteArray4intL(byte[] byteArray) throws StringIndexOutOfBoundsException {  
        int num = byteArray[0] & 0xFF;  
        num 
[解决办法]
= ((byteArray[1] << 8) & 0xFF00);  
        num 
[解决办法]
= ((byteArray[2] << 16) & 0xFF0000);  
        num 
[解决办法]
= ((byteArray[3] << 24) & 0xFF000000);  
        return num;  
    }

[解决办法]
http://www.360doc.com/content/06/0809/10/8473_177064.shtml
[解决办法]
java.nio.ByteBuffer.wrap(bytes).getShort();