In java, byte array and int type conversion (two methods), byteint
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.
Method 1
/*** Int to byte [] * @ param I * @ return */public static byte [] intToByteArray (int I) {byte [] result = new byte [4]; // result [0] = (byte) (I> 24) & 0xFF); result [1] = (byte) (I> 16) & 0xFF); result [2] = (byte) (I> 8) & 0xFF); result [3] = (byte) (I & 0xFF ); return result;}/*** byte [] to int * @ param bytes * @ return */public static int byteArrayToInt (byte [] bytes) {int value = 0; // from high to low for (int I = 0; I <4; I ++) {int shift = (4-1-I) * 8; value + = (bytes [I] & 0x000000FF) <shift; // to high game} 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 2
/*** This method can be used to convert the string, float, and char types to the byte type * @ param args */public static void main (String [] args) {ByteArrayOutputStream baos = new ByteArrayOutputStream (); DataOutputStream dos = new DataOutputStream (baos); try {// int to convert byte array dos. writeByte (-12); dos. writeLong (12); dos. writeChar ('1'); dos. writeFloat (1.01f); dos. writeUTF ("good");} catch (IOException e) {e. printStackTrace ();} byte [] aa = baos. toByteArray (); ByteArrayInputStream bais = new ByteArrayInputStream (baos. toByteArray (); DataInputStream dis = new DataInputStream (bais); // byte converts 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 (); dis. close ();} catch (IOException e) {e. printStackTrace ();}}