Float swap using bswap produces different values

vinoB akashvino79 at gmail.com
Mon Oct 14 15:59:07 UTC 2024


Hi All,

Request your help in understanding why the below code is 
producing different outputs, code 1 output: 4294966806, code 2/3 
output: 50331648, and which one is the correct output.

```d
import std.stdio;

auto floatswap(T)(T[] array) @trusted @nogc pure nothrow
{
     foreach (ref item; array)
     {
         import core.bitop : bswap;
         // Code 1 output: 4294966806
         const swapped1 = bswap(*cast(uint*)&item);
         item = *cast(const(T)*)&swapped1;
         return cast(uint) item;

         // Code 2 output: 50331648
         uint tmp = cast(uint) item;
         tmp = bswap(tmp);
         uint swapped2 = cast(float) tmp;
         return swapped2;

         // Code 3 output: 50331648
         return bswap(cast(uint) item);
      }
     return assert(false, "Unsupported T: " ~ T.stringof);
}

void main () {
     float[1] floatswapBuffer = [3.14f];
     writeln(floatswap(floatswapBuffer[]));
}
```




More information about the Digitalmars-d-learn mailing list