title: How to convert binary string to the byte array of 2 bytes in java
body: <p>I have binary string <code>String A = "1000000110101110"</code>. I want to convert this string into byte array of length 2 in <code>java</code></p>
  
  <p>I have taken the help of <a href="https://stackoverflow.com/questions/17727310/convert-binary-string-to-byte-array">this</a> link</p>
  
  <p>I have tried to convert it into byte by various ways </p>
  
  <ol>
  <li><p>I have converted that string into decimal first and then apply the code to store into the byte array</p>
  
  <pre><code>int aInt = Integer.parseInt(A, 2);
          byte[] xByte = new byte[2];
      xByte[0] = (byte) ((aInt &gt;&gt; 8) &amp; 0XFF);
      xByte[1] = (byte) (aInt &amp; 0XFF);
      System.arraycopy(xByte, 0, record, 0,
              xByte.length);
  </code></pre></li>
  </ol>
  
  <p>But the values get store into the byte array are negative</p>
  
  <pre><code>xByte[0] :-127
  xByte[1] :-82
  </code></pre>
  
  <p>Which are wrong values.</p>
  
  <p>2.I have also tried using </p>
  
  <pre><code>byte[] xByte = ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN).putInt(aInt).array();
  </code></pre>
  
  <p>But it throws the exception at the above line like</p>
  
  <pre><code>  java.nio.Buffer.nextPutIndex(Buffer.java:519)     at
    java.nio.HeapByteBuffer.putInt(HeapByteBuffer.java:366)   at
    org.com.app.convert.generateTemplate(convert.java:266)
  </code></pre>
  
  <p>What should i do now to convert the binary string to byte array of 2 bytes?Is there any inbuilt function  in <code>java</code> to get the byte array</p>