Note that there are some explanatory texts on larger screens.

plurals
  1. POConvert big endian to little endian when reading from a binary file
    primarykey
    data
    text
    <p>I've been looking around how to convert big-endian to little-endians. But I didn't find any good that could solve my problem. It seem to be there's many way you can do this conversion. Anyway this following code works ok in a big-endian system. But how should I write a conversion function so it will work on little-endian system as well?</p> <p>This is a homework, but it just an extra since the systems at school running big-endian system. It's just that I got curious and wanted to make it work on my home computer also</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; using namespace std; int main() { ifstream file; file.open("file.bin", ios::in | ios::binary); if(!file) cerr &lt;&lt; "Not able to read" &lt;&lt; endl; else { cout &lt;&lt; "Opened" &lt;&lt; endl; int i_var; double d_var; while(!file.eof()) { file.read( reinterpret_cast&lt;char*&gt;(&amp;i_var) , sizeof(int) ); file.read( reinterpret_cast&lt;char*&gt;(&amp;d_var) , sizeof(double) ); cout &lt;&lt; i_var &lt;&lt; " " &lt;&lt; d_var &lt;&lt; endl; } } return 0; } </code></pre> <p><strong>Solved</strong></p> <p>So Big-endian VS Little-endian is just a reverse order of the bytes. This function i wrote seem to serve my purpose anyway. I added it here in case someone else would need it in future. This is for double only though, for integer either use the function torak suggested or you can modify this code by making it swap 4 bytes only.</p> <pre><code>double swap(double d) { double a; unsigned char *dst = (unsigned char *)&amp;a; unsigned char *src = (unsigned char *)&amp;d; dst[0] = src[7]; dst[1] = src[6]; dst[2] = src[5]; dst[3] = src[4]; dst[4] = src[3]; dst[5] = src[2]; dst[6] = src[1]; dst[7] = src[0]; return a; } </code></pre>
    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