2011年12月17日土曜日

[JAVA] Java 各种类型间的转换

1. List<Integer> ---> int[]
private int[] toIntArray(List<Integer> list) {
    int[] ret = new int[list.size()];
    int i = 0;
    for (Integer e : list)
        ret[i++] = e.intValue();

    return ret;
}

2. byte[] ---> int[]
public int[] convertByteArrToIntArr(byte[] byteArr) {
    if (byteArr.length % 4 != 0) {
        throw new RuntimeException();
    }

    // 把字节数组转化为int[]后保留的个数.
    int[] intArr = new int[byteArr.length / 4];

    int ch1, ch2, ch3, ch4;
    for (int j = 0, k = 0; j < intArr.length; j++, k += 4) {
        ch1 = byteArr[k];
        ch2 = byteArr[k + 1];
        ch3 = byteArr[k + 2];
        ch4 = byteArr[k + 3];

        // 以下内容用于把字节的8位, 不按照正负, 直接放到int的后8位中.
        if (ch1 < 0) ch1 = 256 + ch1;
        if (ch2 < 0) ch2 = 256 + ch2;
        if (ch3 < 0) ch3 = 256 + ch3;
        if (ch4 < 0) ch4 = 256 + ch4;

        intArr[j] = (ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0);
    }

    return intArr;
}

3. int[] ---> byte[]
public byte[] convertIntArrToByteArr(int[] intArr) {
    byte[] byteArr = new byte[intArr.length * 4];

    int curInt = 0;
    for (int j = 0, k = 0; j < intArr.length; j++, k += 4) {
        curInt = intArr[j];
        byteArr[k] = (byte) ((curInt >>> 24) & 0xFF);
        byteArr[k + 1] = (byte) ((curInt >>> 16) & 0xFF);
        byteArr[k + 2] = (byte) ((curInt >>> 8) & 0xFF);
        byteArr[k + 3] = (byte) ((curInt >>> 0) & 0xFF);
    }

    return byteArr;
}

0 件のコメント:

コメントを投稿