public static int byteArrayToInt(byte[] b) {
        if (b != null && (b.length == 2 || b.length == 4)) {
            // Preserve sign on first byte
            int value = b[0] << ((b.length - 1) * 8);

            for (int i = 1; i < b.length; i++) {
                int offset = (b.length - 1 - i) * 8;
                value += (b[i] & 0xFF) << offset;
            }
            return value;
        } else {
            throw new IllegalArgumentException(
                    "Byte array is null or invalid length.");
        }
    }
@Test
    public void testByteArrayToInt() throws Exception {
        byte[] ba;

        ba = new byte[] { 0, 0 };
        assertEquals(0, TCPClientDecorator.byteArrayToInt(ba));

        ba = new byte[] { 0, 15 };
        assertEquals(15, TCPClientDecorator.byteArrayToInt(ba));

        ba = new byte[] { 0, -1 };
        assertEquals(255, TCPClientDecorator.byteArrayToInt(ba));

        ba = new byte[] { 1, 0 };
        assertEquals(256, TCPClientDecorator.byteArrayToInt(ba));

        ba = new byte[] { -1, -1 };
        assertEquals(-1, TCPClientDecorator.byteArrayToInt(ba));

        ba = new byte[] { 0, 0, -1, -1 };
        assertEquals(65535, TCPClientDecorator.byteArrayToInt(ba));

        ba = new byte[] { 0, 1, 0, 0 };
        assertEquals(65536, TCPClientDecorator.byteArrayToInt(ba));

        ba = new byte[] { 0, 0, 0, 0 };
        assertEquals(0, TCPClientDecorator.byteArrayToInt(ba));

        ba = new byte[] { -128, 0, 0, 0 };
        assertEquals(Integer.MIN_VALUE, TCPClientDecorator.byteArrayToInt(ba));

        ba = new byte[] { 127, -1, -1, -1 };
        assertEquals(Integer.MAX_VALUE, TCPClientDecorator.byteArrayToInt(ba));

        // test invalid byte arrays
        try {
            TCPClientDecorator.byteArrayToInt(null);
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException expected){
            // ignored
        }

        try {
            TCPClientDecorator.byteArrayToInt(new byte[]{});
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException expected){
            // ignored
        }

        try {
            TCPClientDecorator.byteArrayToInt(new byte[]{0});
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException expected){
            // ignored
        }

        try {
            TCPClientDecorator.byteArrayToInt(new byte[]{0,0,0});
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException expected){
            // ignored
        }

        try {
            TCPClientDecorator.byteArrayToInt(new byte[]{0,0,0});
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException expected){
            // ignored
        }
    }