Byte Order Swapping Function

Christian Manning cmanning999 at gmail.com
Sat Jul 16 07:17:58 PDT 2011


Andrew Wiley wrote:

> On Sat, Jul 16, 2011 at 6:21 AM, Christian Manning
> <cmanning999 at gmail.com>wrote:
> 
>> Jonathan M Davis wrote:
>>
>> > On Thursday 14 July 2011 06:27:47 Andrei Alexandrescu wrote:
>> >> On 7/14/11 5:51 AM, Regan Heath wrote:
>> >> > That's my point. I need 8/16/32/64/128 bit versions and it really
>> would
>> >> > be better if there were general variants. My version are less than
>> >> > optimal, but do use intrinsics where possible. Someone else can do a
>> >> > far better job than I, and it really should be done once, by that
>> >> > person. Surely we have the infrastructure for someone to add this to
>> >> > phobos? If something this simple can't or won't be done, what hope
>> >> > do we have!?
>> >>
>> >> I think we should have these functions in std.bitmanip:
>> >>
>> >> T toBigEndian(T)(T val) if (isArithmetic!T || isSomeChar!T);
>> >> T toLittleEndian(T)(T val) if (isArithmetic!T || isSomeChar!T);
>> >> T bigEndianToNative(T)(T val) if (isArithmetic!T || isSomeChar!T);
>> >> T littleEndianToNative(T)(T val) if (isArithmetic!T || isSomeChar!T);
>> >>
>> >> That means all characters, all integers, and all floating point
>> >> numbers. The implementations would opportunistically use intrinsics
>> >> and other specialized means.
>> >>
>> >> The documentation should specify the relationship to htonl and ntohl.
>> >>
>> >> If there's a need for converting endianness of larger buffers, we
>> >> might add:
>> >>
>> >> ubyte[] toBigEndian(ubyte[] val);
>> >> ubyte[] toLittleEndian(ubyte[] val);
>> >> ubyte[] bigEndianToNative(ubyte[] val);
>> >> ubyte[] littleEndianToNative(ubyte[] val);
>> >>
>> >> They'd use std.algorithm.reverse internally as needed.
>> >>
>> >> It's a sweet piece of work. Anyone have the time to prepare a pull
>> >> request?
>> >
>> > I decided to take a crack at it, and it seems to be going pretty well,
>> > except that I can't seem to get the floating point values right.
>> > Somehow, when I compare a floating point value with the same value
>> > except that
>> it's
>> > had its endianness swapped twice, they return true for is but false for
>> > ==, which makes absolutely no sense to me. There's obviously either
>> > something that I don't understand about floating point values (or the
>> > relationship between is and ==) or a bug in dmd. It'd be one thing if I
>> > couldn't get the values to reverse properly, but when they're equal
>> > according to is but not ==, I have no idea how that could even be
>> > possible.
>> >
>> > - Jonathan M Davis
>>
>> I've managed to get floating points working with unions. How are you
>> doing it? Maybe you're triggering a bug somewhere
>>
> 
> After you swap it, do you return the result as a double or as a long?

I return the same type as I was given as input.


More information about the Digitalmars-d mailing list