Mega Code Archive

 
Categories / Java / Data Type
 

Convert int and short to bytes

public class Util{   public static int bytesToInt(byte[] data) {     int value=(data[3] & 0xff);     value =value << 8;     value|=(data[2] & 0xff);     value <<= 8;     value|=(data[1] & 0xff);     value <<= 8;     value|=(data[0] & 0xff);     return value;   }         public static byte[] intTobytes(int value) {     byte[] bytes = new byte[4];     intTobytes(value, bytes);     return bytes;   }   public static void intTobytes(int value, byte[] bytes) {     bytes[3] = (byte) (value >> 24 & 0xff);     bytes[2] = (byte) (value >> 16 & 0xff);     bytes[1] = (byte) (value >> 8 & 0xff);     bytes[0] = (byte) (value & 0xff);   }      public static void shortTobytes(short value, byte[] bytes) {     bytes[1] = (byte) (value >> 8 & 0xff);     bytes[0] = (byte) (value & 0xff);   }         public static short bytesToShort(byte[] data) {     short value=(short) (data[1] & 0xff);     value <<= 8;     value|=(data[0] & 0xff);     return value;   } }