little/big endian conversions

Bill Baxter dnewsgroup at billbaxter.com
Tue Apr 8 03:53:01 PDT 2008


Regan Heath wrote:
> lurker wrote:
>> does anybody know how to convert float and doubles to little/big endian?
> 
> This is a guess but if you read:
> http://en.wikipedia.org/wiki/IEEE_754
> 
> You'll see the internal representation of a float, given that and a 
> little guess work I've come up with:
> 
> import std.stdio;
> 
> int extractSign(float f)
> {
>     return (*(cast(int*)&f) & 0x80000000) ? -1 : 1;
> }
> 
> ubyte extractExp(float f)
> {
>     return (*(cast(int*)&f) << 1) & 0xFF000000;
> }
> 
> int extractFraction(float f)
> {
>     return *(cast(int*)&f) & 0x007FFFFF;
> }
> 
> void main()
> {
>     float f = -1.25f;
>     
>     auto   sign     = extractSign(f);
>     auto   exp      = extractExp(f);
>     auto   fraction = extractFraction(f);
>     
>     writefln(f);
>     writefln(sign);
>     writefln(exp);
>     writefln(fraction);   
> }
> 
> which will extract the various parts of a float.
> 
> Now, I have no idea how they might change on a big/little endian system 
> but I suspect each part would have it's byte order swapped.  In which 
> case, byte order swapping the extracted parts then re-assembling might 
> give you a byte order swapped float.
> 
> Like I said, I'm guessing.
> 
> What you want is 2 systems with different ordering and then you want to 
> dump the content of the float like this:
> 
> writefln("%032b", *(cast(int*)&f));
> 
> then compare.
> 
> Regan


It doesn't matter that it's in IEEE 745 format.  You just swap the bytes 
like it was any old kind of data.

--bb


More information about the Digitalmars-d-learn mailing list