www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Float swap using bswap produces different values

reply vinoB <akashvino79 gmail.com> writes:
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[]));
}
```
Oct 14
parent reply user1234 <user1234 12.de> writes:
On Monday, 14 October 2024 at 15:59:07 UTC, vinoB wrote:
 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.

 [...]
`cast(unint)` of a `float` does truncation. So none of your version is correct. See https://dlang.org/spec/expression.html#cast_floating, paragraph 2.
Oct 14
parent user1234 <user1234 12.de> writes:
On Monday, 14 October 2024 at 20:38:38 UTC, user1234 wrote:
 On Monday, 14 October 2024 at 15:59:07 UTC, vinoB wrote:
 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.

 [...]
`cast(unint)` of a `float` does truncation. So none of your version is correct. See https://dlang.org/spec/expression.html#cast_floating, paragraph 2.
Well "Code 1" does the right thing expected for the cast on the return which wastes it.
Oct 14