Byte Order Swapping Function

Steven Schveighoffer schveiguy at yahoo.com
Thu Jul 14 04:14:51 PDT 2011


On Thu, 14 Jul 2011 06:16:37 -0400, David Nadlinger <see at klickverbot.at>  
wrote:

> On 7/14/11 12:05 PM, Jonathan M Davis wrote:
>> On Thursday 14 July 2011 10:55:49 Regan Heath wrote:
>>> On Thu, 14 Jul 2011 08:14:10 +0100, Jonathan M  
>>> Davis<jmdavisProg at gmx.com>
>>>
>>> wrote:
>>>> I did have to create a 64-bit version for std.datetime, so it has a
>>>> private
>>>> function called endianSwap64 to do the job. So, it's not like I'm  
>>>> saying
>>>> that
>>>> the situation couldn't be improved, but druntime and Phobos do  
>>>> currently
>>>> give
>>>> you the exact same thing that C and C++ do.
>>>
>>> The crypto library I have been meaning to polish up and submit for
>>> inclusion into phobos needs these functions in several variants.  I was
>>> hoping they could/would be included somewhere more 'general' at some
>>> stage, and any duplicates like those already mentioned removed..
>>
>> Oh, it could be done, and it probably should be done. But other than  
>> the 64-
>> bit version (since it's not particularly standard in C or C++), the  
>> functions
>> are there if you need them.
>
> Just for the record, I have my own version for 2/4/8 bytes as well, e.g.  
> at  
> https://github.com/klickverbot/thrift/blob/d-gsoc/lib/d/src/thrift/protocol/base.d#L436.  
> I would appreciate if we could add a general (but fast for the common  
> cases) version to Phobos.

I like your implementation.  However, there are a couple things:

1. doing this:  (t & 0xff00) >> 8 is subject to sign extension, it's  
better to do (t >> 8) & 0x00ff.  I think your current code has a bug for  
the value cast(short)-10000, and in fact, any negative short less than -1.
2. in the 64-bit version, you are probably better off using bswap directly  
instead of calling byteSwap recursively for the upper 32 bits, no?

Also, there should probably be a higher priority branch that will call a  
member function if it exists on the type (think in terms of custom integer  
types).

-Steve


More information about the Digitalmars-d mailing list