Byte Order Swapping Function

Jonathan M Davis jmdavisProg at gmx.com
Thu Jul 14 09:02:12 PDT 2011


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.

Well, it's questionable as to whether there's any point in having such 
functions for 8-bit values, since it would just return the original value. And 
I don't think that it should deal with floating point numbers, since they're 
not affected by endian-ness.

> The documentation should specify the relationship to htonl and ntohl.

Yes, it would be good for the documentation to explain how they relate to 
htonl and ntohl, but realistically, I would think that htonl and ntohl 
could/should then disappear from D code.

> 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.

Given that all you need to do is use std.algorithm.reverse, it seems a bit 
pointless to me to add these for ubyte[]. You'd just be creating aliases, or 
what would amount to them. The ones for 16-bit - 64-bit integral values 
(including wchar and dchar) make good sense, but the others seem a bit 
superfluous.

- Jonathan M Davis


More information about the Digitalmars-d mailing list