title: Java ByteBuffer -> [NSData bytes] to UInt16
body: <p>Good day to all.</p>
  
  <p>I'm writing a client-server application based on sockets. Server is written with Java, client - with Objective-C on iOS SDK 7.</p>
  
  <p>My server writes data to a connected socket with the next code:</p>
  
  <pre><code>//Socket client = new ...;
  DataOutputStream out = new DataOutputStream(client.getOutputStream());
  // send package
  String message = "pings"; // package body
  byte bodySize = (byte) message.length();
  java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocate(2 + 2 + 1 + bodySize);
  buffer.putShort((short) 16); // package ID (2 bytes)
  buffer.putShort((short) 7); // package header (2 bytes, bitmask options)
  buffer.put(bodySize); // calculate &amp; put body size in 5th byte (1 byte)
  buffer.put(message.getBytes()); // put the message to buffer (+5 bytes)
  
  out.write(buffer.array()); // write to stream
  out.close(); // close stream
  </code></pre>
  
  <p>Then I'm trying to parse accepted NSData in Objective-C client. Here's the code:</p>
  
  <pre><code>- (UInt16)packageIdFromPackageHead:(NSData *)data {
      const void *bytes = [data bytes];
      UInt16 packageId;
      memcpy(&amp;packageId, bytes + 0, 2); // get first 2 bytes, it must be short = 16
      return packageId;
  }
  </code></pre>
  
  <p>But, in the "packageId" variable I have the value "4096". What is this? Where is my 16 decimal value?</p>
  
  <p>Next, I'm trying to get the next value, "package header". I wrote the following code:</p>
  
  <pre><code>UInt16 header;
  memcpy(&amp;header, bytes + 2, 2); // skip first 2 bytes, copy next 2 bytes, must be short = 7
  </code></pre>
  
  <p>I got a huge value, 1792. Why? What is this number means? I tried several offsets, +2, +3 - nothing. I can't get a correct value.  I tried to use some conversion as</p>
  
  <pre><code>header = CFSwapInt32BigToHost(header);
  </code></pre>
  
  <p>or</p>
  
  <pre><code>header = CFSwapInt32HostToBig(header);
  </code></pre>
  
  <p>This leads to nothing - I got 0 every time after conversion.</p>
  
  <p>Next, when I tried to get the 5th byte (it contains our message string length, you remember). Here's the code:</p>
  
  <pre><code>UInt8 bodySize;
  memcpy(&amp;bodySize, bytes + 4, 1); // get the 5th byte
  </code></pre>
  
  <p>I got the value</p>
  
  <pre><code>'\x05'
  </code></pre>
  
  <p>And it is correct.</p>
  
  <p>I'm almost certain that the input NSData * value is correct. Here you can see the memory dump screenshot from Xcode:</p>
  
  <p><a href="http://piccy.info/view3/6516579/387eda1d3ca7bb32ca913dbe6d00585f/" rel="nofollow">Debug mode. Input NSData * memory dump</a></p>
  
  <p>Where is a problem? In the server code? Or in my client reading code? Please help, I spent 2 days to find a solution and I still couldn't get it.</p>