Note that there are some explanatory texts on larger screens.

plurals
  1. POHow bit endianness affects bitwise shifts and file IO in C?
    primarykey
    data
    text
    <p>Let <strong>L</strong> and <strong>B</strong> be two machines. <strong>L</strong> order its <em>bits</em> from LSB (Least Significant Bit) to MSB (Most Significant Bit) while <strong>B</strong> order from MSB to LSB. Or, in other words, <strong>L</strong> uses Little Endian while <strong>B</strong> uses Big Endian <em>bit</em> - not to be confused with byte - ordering.</p> <p>Problem 1 <strong>SOLVED</strong>:</p> <p>We are writing the following code which we want to be portable:</p> <pre><code>#include &lt;stdio.h&gt; int main() { unsigned char a = 1; a &lt;&lt;= 1; printf("a = %d\n", (int) a); return 0; } </code></pre> <p>on <strong>L</strong>, it will print 2, but what happens on <strong>B</strong>? Will it shift the 1 out and print 0?.</p> <p><strong>SOLUTION:</strong> The C99 definition at 6.5.7 says it that, at least on unsigned integer types, <code>&lt;&lt;</code> and <code>&gt;&gt;</code> will multiply and divide by 2 respectively.</p> <p>Problem 2:</p> <p>We are writing the following code which we want to be portable:</p> <p>READ program:</p> <pre><code>/* program READ */ #include &lt;stdio.h&gt; int main() { FILE* fp; unsigned char a; fp = fopen("data.dat", "rb"); fread(&amp;a, 1, 1, fp); fclose(fp); return 0; } </code></pre> <p>and WRITE program:</p> <pre><code>/* program WRITE */ #include &lt;stdio.h&gt; int main() { FILE* fp; unsigned char a = 1; fp = fopen("data.dat", "wb"); fwrite(&amp;a, 1, 1, fp); fclose(fp); return 0; } </code></pre> <p>what happens if we run WRITE on <strong>L</strong>, move the data file to <strong>B</strong> and run READ there? And if we run WRITE on <strong>B</strong> and then READ on <strong>L</strong>?</p> <p>Sorry if this is a FAQ. I googled for hours without luck.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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