交换浮点数组中的字节

swapping bytes in float array

本文关键字:字节 数组 交换      更新时间:2023-10-16

我目前正在研究一种二进制文件格式,其中数据表示为浮点数数组,并且数据始终应该使用小端表示形式写入。所以,目前我做以下事情:

float * swapped_array = new float[length_of_array];
for (int i = 0; i < length_of_array; ++i) {
    swapped_array[i] = swap_float(input_array[i]);
}

在这里,swap_float交换浮点值的四个字节。现在,我想知道是否有一种方法可以跨平台的方式做到这一点,而无需迭代使用它 for 循环并使其计算效率更高。

在我看来,

您可以使用一些指针算法来交换字节:

byte mem;
byte* first = (byte*) floatpointer;
mem = *first;
*first = *(first+0x03);
*(first+0x03) = mem;
first++;
mem = *first;
*first = *(first+0x01);
*(first+0x01) = mem;