title: Converting binary reading function from C# to C
body: <p>I am honestly really confused on reading binary files in C.</p>
  
  <p>My data is in a format like: </p>
  
  <ul>
  <li>int header</li>
  <li>Cell[][] cells, 8x8 matrix</li>
  <li>Each cell is just a short id and a sbyte z.</li>
  </ul>
  
  <p>However, something is clearly messing up and none of the values are accurate.</p>
  
  <pre><code>  int i, j;
    Block block;
  
    // read 32 bits
    fread( &amp;(block.header), sizeof( int ), 1, mapFile );
  
    // loop through to fill the 8x8 matrix
    for( i = 0; i &lt; 8; i++ )
    {
      for( j = 0; j &lt; 8; j++ )
      {
        // read 16 bits
        fread( &amp;(block.cells[i][j].tileId), sizeof( short ), 1, mapFile );
        // read 8 bits
        fread( &amp;(block.cells[i][j].z), sizeof( char ), 1, mapFile );
  
        printf( "[%i][%i]: %x %i", i, j, block.cells[i][j].tileId, block.cells[i][j].z );
      }
    }
    printf( "header: %i", block.header );
  </code></pre>
  
  <p>Output of above shows a bunch of lines with <code>[n][n]: ffffa800 251</code>.</p>
  
  <p>My C# version works fine though:</p>
  
  <pre><code>            Block block;
              block.header = reader.ReadInt32();
              block.cells = new Cell[8,8];
              for( int i = 0; i &lt; 8; i++ )
              {
                  for ( int j = 0; j &lt; 8; j++ )
                  {
                      block.cells[i, j].tileId = reader.ReadInt16();
                      block.cells[i, j].z = reader.ReadSByte();
                  }
              }
  
              reader.Close();
  </code></pre>
  
  <p>Output from that (correctly) shows <code>[n][n]: a8 -5</code>.</p>