Byte Order Swapping Function
KennyTM~
kennytm at gmail.com
Sun Jul 17 01:09:13 PDT 2011
On Jul 17, 11 15:44, Jonathan M Davis wrote:
> On Sunday 17 July 2011 15:31:36 KennyTM~ wrote:
>> On Jul 17, 11 05:51, Jonathan M Davis wrote:
>>> On Saturday 16 July 2011 15:38:29 Andrei Alexandrescu wrote:
>>>> Just paste the code here.
>>>
>>> This is what I have at the moment:
>>>
>>> import core.bitop;
>>
>> [snip]
>>
>>> private T swapEndianImpl(T)(T val)
>>>
>>> if(is(Unqual!T == ulong))
>>>
>>> {
>>>
>>> return ((val& 0xff00000000000000UL)>> 56) |
>>>
>>> ((val& 0x00ff000000000000UL)>> 40) |
>>> ((val& 0x0000ff0000000000UL)>> 24) |
>>> ((val& 0x000000ff00000000UL)>> 8) |
>>> ((val& 0x00000000ff000000UL)<< 8) |
>>> ((val& 0x0000000000ff0000UL)<< 24) |
>>> ((val& 0x000000000000ff00UL)<< 40) |
>>> ((val& 0x00000000000000ffUL)<< 56);
>>>
>>> }
>>
>> Why not just 'bswap' the two uint parts?
>
> If that will work sure, but thinking about it, I couldn't think of how you
> could use bswap like that. bswap swaps the 4 bytes that it's given. But you
> have to swap each end with each end, not an end with the middle. So, it's not
> like you can use bswap on half of it and then on the other half. I suppose
> that you could use bswap for the middle 4 bytes and then bitshifts for the 2
> bytes on each side, and that would probably be faster. But I don't see how you
> could use bswap to swap any two pieces of a 64-bit integer and properly swap
> it. Now, it may very well be possible and I just don't see it, but I don't see
> it. So, if you know how, please tell me.
>
> - Jonathan M Davis
import core.bitop;
private ulong swapEndianImpl(ulong val) {
ulong res = bswap(val & 0xffff_ffff);
return res << 32 | bswap(val >> 32);
}
unittest {
assert(swapEndianImpl(0xfedcba98_76543210UL) == 0x10325476_98badcfeUL);
}
More information about the Digitalmars-d
mailing list