-2

我有一个偶数长度的 byte[] 数组。现在,我希望 byte[] 数组分成其长度的一半,其中 byte[] 数组中的前两个字节作为字节 b1,接下来的两个作为字节 b2,依此类推。

请帮忙。谢谢

4

2 回答 2

0

这是作业吗?我猜你的主要问题是将字节对组合成双字节。这是通过所谓的左移 ( <<) 实现的,字节为 8 位,因此移位八位:

int doubleByte = b1 + (b2 << 8);

请注意,我b1用作低字节和b2高字节。

剩下的很简单:分配一个int长度为字节数组一半的数组,然后遍历字节数组以构建新int数组。希望这可以帮助。

于 2012-06-25T08:46:30.143 回答
0

也许我完全理解你的问题是错误的。

public class Main {
    // run this
    public static void main(String[] args) {    

        // create the array and split it
        Main.splitArray(new byte[10]);
    }

    // split the array
    public static void splitArray(byte[] byteArray) {
        int halfSize = 0; // holds the half of the length of the array
        int length = byteArray.length; // get the length of the array
        byte[] b1 = new byte[length / 2]; // first half
        byte[] b2 = new byte[length / 2]; // second half
        int index = 0;

        if (length % 2 == 0) { // check if the array length is even
            halfSize = length / 2; // get the half length

            while (index < halfSize) { // copy first half
                System.out.println("Copy index " + index + " into b1's index " + index);
                b1[index] = byteArray[index];
                index++;
            }

            int i = 0; // note the difference between "i" and "index" !
            while (index < length) { // copy second half
                System.out.println("Copy index " + index + " into b2's index " + i);// note the difference between "i" and "index" !
                b2[i] = byteArray[index];// note the difference between "i" and "index" !
                index++;
                i++; //dont forget to iterate this, too
            }

        } else {
            System.out.println("Length of array is not even.");
        }
    }
}
于 2012-06-25T09:28:04.953 回答