The conversion of byte array and int type in Java. In network programming, this algorithm is the most basic algorithm. We all know that in socket transmission, the data sent and received by the sender are all byte arrays, but the int type is composed of 4 bytes. How to convert a shaping int into a byte array, and how to convert a byte array of length 4 to an int type. There are two ways below.
public static byte[] int2byte(int res) {byte[] targets = new byte[4];targets[0] = (byte) (res & 0xff);// Lowest bit targets[1] = (byte) ((res >> 8) & 0xff);// Secondary low bit targets[2] = (byte) ((res >> 16) & 0xff);// Secondary high bit targets[3] = (byte) (res >>> 24);// Highest bit, unsigned right shift. return targets; } public static int byte2int(byte[] res) { // A byte data is shifted 24 bits left to 0x??000000, and then 8 bits right to 0x00??00000 int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00) // | Indicates ambient or | ((res[2] << 24) >>> 8) | (res[3] << 24); return targets; }The second type
public static void main(String[] args) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); try { dos.writeByte(4); dos.writeByte(1); dos.writeByte(1); dos.writeShort(217); } catch (IOException e) { e.printStackTrace(); } byte[] aa = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); DataInputStream dis = new DataInputStream(bais); try { System.out.println(dis.readByte()); System.out.println(dis.readByte()); System.out.println(dis.readByte()); System.out.println(dis.readShort()); } catch (IOException e) { e.printStackTrace(); } try { dos.close(); dis.close(); } catch (IOException e) { e.printStackTrace(); } }The above article is based on the conversion of byte array and int type in Java (two methods) which is all the content I share with you. I hope it can give you a reference and I hope you can support Wulin.com more.