2

I am currently working on a binary file format where the data is represented as an array of floats and the data is always supposed to be written with the little endian representation. So, currently I do something as follows:

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]);
}

Here the swap_float swaps the four bytes of the floating point value. Now, I was wondering if there is a way to do this in a cross platform way without iterating using this for loop and making it more computationally efficient.

Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465
Luca
  • 9,398
  • 15
  • 84
  • 201

1 Answers1

2

Looks to me you can swap the bytes by using some pointer arithmetic:

byte mem;
byte* first = (byte*) floatpointer;
mem = *first;
*first = *(first+0x03);
*(first+0x03) = mem;
first++;
mem = *first;
*first = *(first+0x01);
*(first+0x01) = mem;
Willem Van Onsem
  • 397,926
  • 29
  • 362
  • 485