Boost logo

Boost Users :

Subject: Re: [Boost-users] handle different endian
From: Scott McMurray (me22.ca+boost_at_[hidden])
Date: 2008-12-12 14:28:56


On Fri, Dec 12, 2008 at 12:02, boost001 <oldyoungguy88_at_[hidden]> wrote:
>
> Does Boost have method to do endian swap, like those ntohl and htonl?
>

Beman Dawes was working on an elegant endian-handling library, but
iirc it ran into problems that were only nicely fixable with C++0x
features.

In the mean time, you could implement an endian swap something like this:

#include <boost/detail/endian.hpp>
#include <boost/mpl_assert.hpp>
#include <boost/type_traits/is_integral.hpp>
#include <algorithm>

template <typename T>
T reverse_bytes(T const x) {
    BOOST_MPL_ASSERT((boost::is_integral<T>));
    T y = x;
    std::reverse((char*)(&y), (char*)(1+&y));
    return y;
}

#if defined(BOOST_LITTLE_ENDIAN)
template <typename T>
T hton(T const x) { return reverse_bytes(x); }
template <typename T>
T ntoh(T const x) { return reverse_bytes(x); }
#else
template <typename T>
T hton(T const x) { return x; }
template <typename T>
T ntoh(T const x) { return x; }
#endif

And overload reverse_bytes for anything else you want it to work on.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net