Byte Order Swapping Function

Jonathan M Davis jmdavisProg at gmx.com
Sun Jul 17 01:48:37 PDT 2011


On Sunday 17 July 2011 09:40:06 Alix Pexton wrote:
> On 17/07/2011 07:42, Jonathan M Davis wrote:
> > On Saturday 16 July 2011 23:31:09 Andrew Wiley wrote:
> [snip]
> 
> >> Take a look at http://www.dmh2000.com/cpp/dswap.shtml . It made the
> >> odd
> >> behavior make a lot more sense to me.
> > 
> > Okay. Good to know. In other words, we can't have swapEndian work with
> > floating point values like that. It can generate a byte array from them
> > (or maybe an integral value of the same size), but it can't generate
> > another floating point value. Bleh. Okay. Floating point values with
> > have to use an entirely different overload then. Thanks for the info.
> > 
> > - Jonathan M Davis
> 
> I find myself wanting to address this issue by using types, as the FP
> example demonstrates that when the endieness of a value changes, its
> type should too.
> 
> using double as an example, I'd like to be able to write code something
> like this.
> 
> > auto v0 = 0.1;
> > auto v1 = nbo!double(v0); // nbo = network byte order, your names may
> > vary auto v2 = to!double(v1);
> > assert(v0 == v2);
> 
> I would, of course, expect aliases for those occasions when one wants to
> state endieness explicitly (I just can't think of any >< ), and for
> non-conversions (when nbo == hbo) to be no-ops.
> 
> Or am I missing something?
> 
> A...

I suppose that you _could_ do something like that, though I'm not sure that 
there's much point. You can swap integers with impunity. Having a separate 
type would actually be a problem, because then you'd have to translate to an 
integer again anyway to do anything with it. In the case of a floating point 
value, you essentially have to convert to either an integral value or an array 
of ubytes. You could wrap that in a struct or somesuch, but I'm not sure how 
much point there is in that. Just like with integers, you'd have to convert it 
over to a prmitive type before doing anything with it like sending it via the 
network.

So, sure you _could_ make such types, but I don't think that there's much 
point to it. And if someone wants to do that in their own code, it wouldn't be 
all that hard. The hard part is the actual byte swapping.

- Jonathan M Davis


More information about the Digitalmars-d mailing list