In java, byte array and int type conversion. In network programming, this algorithm is the most basic algorithm. We all know that in socket transmission, the data received by the sender is a byte array, however, the int type is composed of four bytes. How to convert an integer int to a byte array and convert a byte array with a length of 4 to the int type. There are two methods below.
Public static byte [] int2byte (int res ){
Byte [] targets = new byte [4];
Targets [0] = (byte) (res & 0xff); // second bit
Targets [1] = (byte) (res> 8) & 0xff); // low position
Targets [2] = (byte) (res> 16) & 0xff); // high
Targets [3] = (byte) (res >>> 24); // highest bit, unsigned shifted to the right.
Return targets;
}
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();
}
}