In previous projects, when Socket communication, the value of the int type needs to be passed, but outputsteam in Java cannot directly pass the int type, and can only pass byte[], so here I will record the method of int and byte[] to transfer.
/** * int to byte[] */ public static byte[] intToBytes(int i) { byte[] bytes = new byte[4]; bytes[0] = (byte) (i & 0xff); bytes[1] = (byte) ((i >> 8) & 0xff); bytes[2] = (byte) ((i >> 16) & 0xff); bytes[3] = (byte) ((i >> 24) & 0xff); return bytes; }Turn it again when receiving it
/** * byte[] to int */ public static int bytesToInt(byte[] bytes) { int i; i = (int) ((bytes[0] & 0xff) | ((bytes[1] & 0xff) << 8) | ((bytes[2] & 0xff) << 16) | ((bytes[3] & 0xff) << 24)); return i; }The above is the mutual conversion between int and byte[] in Java introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!