title: Transfering uintN data types from C to Java (Socket Programing)
body: <p>I have a requirement to send data from native program written in C through Sockets, namely the winsock interface. That data is then received by a java program. The Java program receives a packet of data of which it know the order and makes some processing. It takes the int received from the socket.Read() like <code>client_socket.getInputStream().read()</code> </p>
  
  <p>A processing of that int data returned from the Read() is parsed to get the data types expected. Basically it is a slicing of the bulk data received. I can only assume that the read() functions reads 4 bytes at a time (the 32 bit java int size). So I proceed to separate that 4 bytes(8 bits not the Java type) into 4 Java shorts so i can correctly represent the unsigned values they represent.
  After i have the 4 shorts if i know i want eg a uint16, i just concatenate the 2 shorts</p>
  
  <p>The problem is somewhere i am doing some wrong bit manipulation that is not working out as i thought it would.
  The C code and the Java code is below and its really simple even though it does not work. The output is something which i can't understand why it is the way it is.</p>
  
  <pre><code>0 0   0 0    0 1     0 0     0 2     0 0     0 3     0 0     0 4 {...}
  </code></pre>
  
  <p>The C code redacted the initialization part:</p>
  
  <pre><code>uint16_t buffer[255] = {};
  uint16_t *current_pointer = buffer;
  for(uint16_t index = 0; index &lt; 255; index++) {
      *current_pointer = index;
      current_pointer++;
  }
  Write(client_socket, (char *)buffer, sizeof(buffer));
  </code></pre>
  
  <p>The java code also redacted:</p>
  
  <pre><code>public final short[] JavaIntToUint8Array(int unsigned_int) {
      return new short[] { (short)((unsigned_int &amp; 0xFF000000L) &gt;&gt; 24),
                  (short)((unsigned_int &amp; 0x00FF0000L) &gt;&gt; 16),
                  (short)((unsigned_int &amp; 0x0000FF00L) &gt;&gt; 8),
                  (short)((unsigned_int &amp; 0x000000FFL))};
  }
  public final int[] JavaIntToUint16(int unsigned_int) {
      short uint8_array[] = JavaIntToUint8Array(unsigned_int);
      return new int[] { (int)(uint8_array[0] &lt;&lt; 8) | (int)uint8_array[1],            
          (int)(uint8_array[2] &lt;&lt; 8) | (int)(uint8_array[3]) };
  }
  </code></pre>
  
  <p>...</p>
  
  <pre><code>while (index &lt; 255) {
          read_data = data_input.read();
          System.out.print(" ");
          System.out.print(JavaIntToUint16(read_data)[0]);
          System.out.print(" ");
          System.out.print(JavaIntToUint16(read_data)[1]);
          System.out.print("\t");
          index++;
  
  }
  </code></pre>