In Java, the conversion of byte array and int type, in network programming this algorithm is the most basic algorithm, we all know, in the socket transmission, send, the data received by the byte array, but the int type is 4 byte, How to convert an int into a byte array, and how to convert a byte array of length 4 to an int type. Here are two ways.
public static byte[] Int2byte (int res) {
byte[] targets = new BYTE[4];
Targets[0] = (byte) (res & 0xff);//lowest bit
targets[1] = (byte) ((res >> 8) & 0xff);/times low
targets[2] = (byte) (res >>) & 0xff);//secondary high
targets[3] = (byte) (res >>> 24);//highest bit, unsigned right shift. return
targets;
}
public static int Byte2int (byte[] res) {
//One byte data shifts left 24 digits to 0x?? 000000, and then move to the right 8 to become 0x00?? 0000
int targets = (Res[0] & 0xff) | ((Res[1] << 8) & 0xff00)//| To indicate an position or
| ((res[2] <<) >>> 8) | (Res[3] <<);
return targets;
Second Kind
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 is based on the Java byte array and int type conversion (two methods) is a small series to share all the content, hope to give you a reference, but also hope that we support cloud habitat community.