Original URL: http://blog.csdn.net/piaojun_pj/article/details/5903009
In Java, the conversion of byte array and int type, in network programming this algorithm is the most basic algorithm, we all know that in the socket transmission, the data received by the sender is a byte array, but the int type is 4 bytes, How to convert an int into a byte array, and how to convert a byte array of length 4 to the int type. There are two ways of doing this.
The first method:
public static byte[] Int2byte (int res) {
Byte[] targets = new BYTE[4];
Targets[0] = (byte) (res & 0xff);//lowest bit
targets[1] = (byte) ((res >> 8) & 0xff);//Sub-low ;
Targets[2] = (byte) ((res >>) & 0xff);//secondary high
targets[3] = (byte) (res >>> 24);//Highest bit, no character Move the number to the right.
return targets;
}
public static int byte2int (byte[] res) {
// A byte data shifted left 24 bits into 0x?? 000000, then move right 8 bits into 0x00?? 0000&NBSP
int targets = (Res[0] & 0xff) | ((Res[1] << 8) & 0xff00)//| Represents an or a-n;
| ((res[2] <<) >>> 8) | (Res[3] <<);
return targets;
}
The second method:
public static byte[] Inttobytearray (int i) throws Exception {
Bytearrayoutputstream buf = new Bytearrayoutputstream ();
DataOutputStream dos= New DataOutputStream (BUF);
Dos.writeint (i);
Byte[] B = Buf.tobytearray ();
Dos.close ();
Buf.close ();
return b;
}
public static int Bytearraytoint (byte b[]) throws Exception {
int temp = 0, a=0;
Bytearrayinputstream buf = new Bytearrayinputstream (b);
DataInputStream dis= New DataInputStream (BUF);
return Dis.readint ();
}
Personal feelings The second method is more commonly used, and it is easier to implement byte arrays with other basic data types (long,float ) to convert each other.
Conversion of byte array to int type in "Go" Java (two ways)----good.