Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I have this code that allow me to convert from HOST_ENDIAN_ORDER (whatever it is) to LITTLE_ENDIAN_ORDER or BIG_ENDIAN_ORDER. I use a template, so if I try to convert from HOST_ENDIAN_ORDER to LITTLE_ENDIAN_ORDER and they happen to be the same for the machine for wich I compile, no code will be generated.</p> <p>Here is the code with some comments:</p> <pre><code>// We define some constant for little, big and host endianess. Here I use // BOOST_LITTLE_ENDIAN/BOOST_BIG_ENDIAN to check the host indianess. If you // don't want to use boost you will have to modify this part a bit. enum EEndian { LITTLE_ENDIAN_ORDER, BIG_ENDIAN_ORDER, #if defined(BOOST_LITTLE_ENDIAN) HOST_ENDIAN_ORDER = LITTLE_ENDIAN_ORDER #elif defined(BOOST_BIG_ENDIAN) HOST_ENDIAN_ORDER = BIG_ENDIAN_ORDER #else #error "Impossible de determiner l'indianness du systeme cible." #endif }; // this function swap the bytes of values given it's size as a template // parameter (could sizeof be used?). template &lt;class T, unsigned int size&gt; inline T SwapBytes(T value) { union { T value; char bytes[size]; } in, out; in.value = value; for (unsigned int i = 0; i &lt; size / 2; ++i) { out.bytes[i] = in.bytes[size - 1 - i]; out.bytes[size - 1 - i] = in.bytes[i]; } return out.value; } // Here is the function you will use. Again there is two compile-time assertion // that use the boost librarie. You could probably comment them out, but if you // do be cautious not to use this function for anything else than integers // types. This function need to be calles like this : // // int x = someValue; // int i = EndianSwapBytes&lt;HOST_ENDIAN_ORDER, BIG_ENDIAN_ORDER&gt;(x); // template&lt;EEndian from, EEndian to, class T&gt; inline T EndianSwapBytes(T value) { // A : La donnée à swapper à une taille de 2, 4 ou 8 octets BOOST_STATIC_ASSERT(sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8); // A : La donnée à swapper est d'un type arithmetic BOOST_STATIC_ASSERT(boost::is_arithmetic&lt;T&gt;::value); // Si from et to sont du même type on ne swap pas. if (from == to) return value; return SwapBytes&lt;T, sizeof(T)&gt;(value); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload