Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to manage endianess of double from network
    primarykey
    data
    text
    <p>I have a BIG problem with the answer to this question <a href="https://stackoverflow.com/questions/2673409/swap-bits-in-c-for-a-double">Swap bits in c++ for a double</a></p> <p>Yet, this question is more or less what I search for: I receive a double from the network and I want to encoded it properly in my machine.</p> <p><br> In the case I receive an <code>int</code> I perform this code using <code>ntohl</code> :</p> <pre><code>int * piData = reinterpret_cast&lt;int*&gt;((void*)pData); //manage endianness of incomming network data unsigned long ulValue = ntohl(*piData); int iValue = static_cast&lt;int&gt;(ulValue); </code></pre> <p>But in the case I receive an <code>double</code>, I don't know what to do.</p> <p>The answer to the question suggest to do:</p> <pre><code>template &lt;typename T&gt; void swap_endian(T&amp; pX) { char&amp; raw = reinterpret_cast&lt;char&amp;&gt;(pX); std::reverse(&amp;raw, &amp;raw + sizeof(T)); } </code></pre> <p>However , if I quote <a href="http://forums.codeguru.com/showthread.php?298741-C-General-What-do-ntohl%28%29-and-htonl%28%29-actually-do" rel="nofollow noreferrer">this site</a>: </p> <p><code>The ntohl() function converts the unsigned integer netlong from network byte order to host byte order. When the two byte orders are different, this means the endian-ness of the data will be changed. When the two byte orders are the same, the data will not be changed.</code> </p> <p>On the contrary @GManNickG's answer to the question <strong>always does the inversion</strong> with <code>std::reverse</code> .</p> <p>Am I wrong considering that this answer is false ? ( in the extent of network management of endianess which the use of <code>ntohl</code> suggest though it was not precisely said in the title of the OP question).</p> <p>In the end: Should I split my <code>double</code> into two parts of 4 bytes and apply the <code>ntohl</code> function on the two parts ? Are there more cannonical solutions ?</p> <p>There's also this interesting question in C, <a href="https://stackoverflow.com/questions/6084279/host-to-network-double">host to network double?</a>, but it limits to 32 bits values. And the answer says doubles should be converted to strings because of architecture differences... I'm also gonna work with audio samples, should I really consider converting all the samples to strings in my database ? ( the doubles come from a database that I query over the network)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

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