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
  • 714,442
  • 84
  • 1,110
  • 1,523
Luca
  • 10,458
  • 24
  • 107
  • 234

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
  • 443,496
  • 30
  • 428
  • 555