我需要将C++中unsigned char的概念移植到Java中,以将字节数组转换为浮点数组

问题描述 投票:0回答:0

我必须将 C++ 代码传输到 Java,在 C++ 中,我有一个 unsigned char 数组,它会转换为一个浮点数数组,其大小为 unsigned char 数组的 1/4(因为它将 4 个字节组合在一起)浮点数组的元素)使用 memcpy 函数,它工作得很好。在Java中,只要我搜索,我们就没有unsigned char,因为byte[]类型仅保留在-128~127之间,然后我使用& 0xFF掩码将值存储在int[]内。所以现在我有一个 int 数组,其中的值需要整形为 int 数组大小 1/4 的浮点数组(我确实知道 Int 有 32 位而不是 8 位,但是我不能说对这个主题有什么影响)。考虑到我拥有的数据,我该怎么做才能在 Java 中实现与 C++ 的 memcpy 相同的结果?

在 C++ 中:

unsigned size = someSize;
unsigned char unsignedCharArray[someSize]; 
//...fullfill unsignedCharArray
float floatArray[0.25*someSize]; 
memcpy(floatArray, unsignedCharArray, size);

我正在尝试用 Java 做什么:

//...declares and fullfill intArray
float[] floatArray = new float[intArray.length/4];
for (int i = 0; i < floatArray.length; i+=4) {
        int firstByte = (byte) intArray[i];
        int secondByte = (byte)  intArray[i + 1];
        int thirdByte = (byte) intArray[i + 2];
        int fourthByte = (byte)  intArray[i + 3];

        int intValue = ((firstByte & 0xFF) << 24 | (secondByte & 0xFF) << 16 | (thirdByte & 0xFF) << 8 | (fourthByte & 0xFF));

        floatArray[i/4] = Float.intBitsToFloat(intValue);
}
java c++ c byte unsigned
© www.soinside.com 2019 - 2024. All rights reserved.