www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Byte Order Swapping Function

reply Andrew Wiley <wiley.andrew.j gmail.com> writes:
Hey, does anyone else thing a function like this belongs in Phobos, and if
so, where do you think it should go?

T ntoh(T)(T val) if (__traits(isArithmetic, T)) {
version(BigEndian) {
 return val;
}
else version (LittleEndian) {
 ubyte[] arr = (cast(ubyte*)&val)[0 .. T.sizeof];
ubyte temp;
for(int i = 0; i < T.sizeof/2; i++) {
 temp = arr[i];
arr[i] = arr[T.sizeof - i - 1];
arr[T.sizeof - i - 1] = temp;
 }
return val;
}
 else static assert(0, "Are you sure you're using a computer?");
 }

I was looking for something along these lines in the docs today and couldn't
find it. It looks like there's a stream in std.stream to do this, but, well,
I think we've all been pretending std.stream doesn't exist for a while now.
Jul 13 2011
parent Johannes Pfau <spam example.com> writes:
Andrew Wiley wrote:
Hey, does anyone else thing a function like this belongs in Phobos,
and if so, where do you think it should go?

T ntoh(T)(T val) if (__traits(isArithmetic, T)) {
version(BigEndian) {
 return val;
}
else version (LittleEndian) {
 ubyte[] arr = (cast(ubyte*)&val)[0 .. T.sizeof];
ubyte temp;
for(int i = 0; i < T.sizeof/2; i++) {
 temp = arr[i];
arr[i] = arr[T.sizeof - i - 1];
arr[T.sizeof - i - 1] = temp;
 }
return val;
}
 else static assert(0, "Are you sure you're using a computer?");
 }

I was looking for something along these lines in the docs today and
couldn't find it.
There's also the bswap intrinsic in core.bitop. This always swaps the byte order and it only works for uint, though. -- Johannes Pfau
Jul 14 2011