Note that there are some explanatory texts on larger screens.

plurals
  1. POByte Array to *Signed* Int
    text
    copied!<p>I'm trying to convert <code>-101</code> to a byte array and then convert the byte array back to <code>-101</code>. My methods below work for positive values but not for negative values. Can you suggest what I'm doing wrong? Instead of <code>-101</code>, the <code>byteArrayToInt</code> method returns <code>65435</code>. Thanks!</p> <pre><code>/** * Converts a &lt;code&gt;byte&lt;/code&gt; array to a 32-bit &lt;code&gt;int&lt;/code&gt;. * * @param array The &lt;code&gt;byte&lt;/code&gt; array to convert. * @return The 32-bit &lt;code&gt;int&lt;/code&gt; value. */ public static int byteArrayToInt(byte[] array) { ValidationUtils.checkNull(array); int value = 0; for (int i = 0; i &lt; array.length; i++) { int shift = (array.length - 1 - i) * 8; value = value | (array[i] &amp; 0xFF) &lt;&lt; shift; } return value; } /** * Converts a 32-bit &lt;code&gt;int&lt;/code&gt; to a &lt;code&gt;byte&lt;/code&gt; array. * * @param value The 32-bit &lt;code&gt;int&lt;/code&gt; to convert. * @return The &lt;code&gt;byte&lt;/code&gt; array. */ public static byte[] intToByteArray(int value, int size) { byte[] bytes = new byte[size]; for (int index = 0; index &lt; bytes.length; index++) { bytes[index] = (byte) (value &gt;&gt;&gt; (8 * (size - index - 1))); } return bytes; } /** * Tests the utility methods in this class. * * @param args None. */ public static void main(String... args) { System.out.println(byteArrayToInt(intToByteArray(32, 2)) == 32); // true System.out.println(byteArrayToInt(intToByteArray(64, 4)) == 64); // true System.out.println(byteArrayToInt(intToByteArray(-101, 2)) == -101); // false System.out.println(byteArrayToInt(intToByteArray(-101, 4)) == -101); // true } </code></pre>
 

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