Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You need to pay attention to the <a href="http://en.wikipedia.org/wiki/Endianness" rel="nofollow">endianness</a> of your architecture, particularly since the behaviour of <a href="http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx" rel="nofollow"><code>BitConverter</code></a> is architecture-dependant. As it stands, your code probably fails when you are transmitting data between architectures of different endianness. Imagine, for example, a message whose size is 241 bytes. The sender – who we shall assume to be big-endian – would indicate this size by sending a byte sequence of <code>[0,0,0,241]</code>. This will be correctly interpreted as 241 on a big-endian receiver, but as 4,043,309,056 (equal to 241×256<sup>3</sup>) on a little-endian one. If you try to allocate a byte array that large, you would most likely get an <code>OutOfMemoryException</code>.</p> <p>Assuming that your incoming stream is always big-endian, you handle this by adapting your code to reverse the array when your architecture is little-endian:</p> <pre><code>buffer = new byte[4]; readBytes = ns.Read(buffer, 0, 4); if (readBytes == 0) return null; if (BitConverter.IsLittleEndian) Array.Reverse(buffer); </code></pre> <p><strong>Edit</strong>: Replying to comment:</p> <p>You need to correct for endianness whenever you’re going to use the <code>BitConverter.ToInt32</code> method to convert a 4-byte sequence into an integer. You don’t need to correct for endianness when using the <code>BinaryFormatter</code>, since it handles endianness transparently.</p> <p>I assume that endianness depends on your machine’s physical architecture, but I’ve never studied the specifics. To be safe, you should never assume a particular endianness, irrespective of whether you’re running on x86 or x64.</p> <p>If you’re responsible for the server code as well, you also need to correct for endianness there. For example, to send the <code>cmdID</code> value from the server:</p> <pre><code>int cmdID = 22; // for the example byte[] buffer = BitConverter.GetBytes(cmdID); if (BitConverter.IsLittleEndian) Array.Reverse(buffer); ns.Write(buffer, 0, 4); </code></pre>
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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