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.
Method One
/** * int to byte[] * @param i * @return */public static byte[] Inttobytearray (int i) {byte[] result = new byte[4];//from high to low R Esult[0] = (byte) ((I >>) & 0xFF); result[1] = (byte) ((I >> +) & 0xFF); result[2] = (byte) ((I > > 8) & 0xFF); result[3] = (byte) (I & 0xFF); return result; /** * byte[] Go int * @param bytes * @return */public static int bytearraytoint (byte[] bytes) {int value = 0;//from high to low for (in t i = 0; I < 4; i++) {int shift = (4-1-i) * 8;value + = (Bytes[i] & 0x000000ff) << shift;//go to high-level tour}return value;} public static void Main (string[] args) {byte[] b = Inttobytearray (128); System.out.println (arrays.tostring (b)); int i = Bytearraytoint (b); System.out.println (i);}
Method Two
/** * This method can convert a String type, float type, char type, and so on to a byte type * @param args */public static void main (string[] args) {bytearrayoutputs Tream BAOs = new Bytearrayoutputstream ();D ataoutputstream dos = new DataOutputStream (BAOs); try {// int converts byte array dos.writebyte ( -12);d Os.writelong (1);d os.writefloat (1.01f);d Os.writeutf ("good");d Os.writechar;} catch (IOException e) {e.printstacktrace ();} byte[] AA = Baos.tobytearray (); Bytearrayinputstream Bais = new Bytearrayinputstream (Baos.tobytearray ());D atainputstream dis = new DataInputStream ( Bais);//Byte conversion inttry {System.out.println (Dis.readbyte ()); System.out.println (Dis.readlong ()); System.out.println (Dis.readchar ()); System.out.println (Dis.readfloat ()); System.out.println (Dis.readutf ());} catch (IOException e) {e.printstacktrace ();} try {dos.close ();d is.close ();} catch (IOException e) {e.printstacktrace ()}}
Conversion of byte array to int type in Java (two ways)