Examples are as follows:
public class DataTypeChangeHelper { /** * Convert a single-byte byte to a 32-bit int * * @param b * byte * @return convert result */ public static int unsignedByteToInt(byte b) { return (int) b & 0xFF; } /** * Convert a single-byte Byte to a hexadecimal number* * @param b * byte * @return convert result */ public static String byteToHex(byte b) { int i = b & 0xFF; return Integer.toHexString(i); } /** * Convert an array of 4bytes into a 32-bit int * * @param buf * bytes buffer * The position in @param byte[] where the conversion starts* @return convert result */ public static long unsigned4BytesToInt(byte[] buf, int pos) { int firstByte = 0; int secondByte = 0; int thirdByte = 0; int fourthByte = 0; int index = pos; firstByte = (0x000000FF & ((int) buf[index])); secondByte = (0x000000FF & ((int) buf[index + 1])); thirdByte = (0x000000FF & ((int) buf[index + 2])); fourthByte = (0x000000FF & ((int) buf[index + 3])); index = index + 4; return ((long) (firstByte << 24 | secondByte << 16 | thirdByte << 8 | fourthByte)) & 0xFFFFFFL; } /** * Convert 16-bit short to byte array* * @param s * short * @return byte[] length is 2 * */ public static byte[] shortToByteArray(short s) { byte[] targets = new byte[2]; for (int i = 0; i < 2; i++) { int offset = (targets.length - 1 - i) * 8; targets[i] = (byte) ((s >>> offset) & 0xff); } return targets; } /** * Convert 32-bit integers into byte arrays with length 4* * @param s * int * @return byte[] * */ public static byte[] intToByteArray(int s) { byte[] targets = new byte[2]; for (int i = 0; i < 4; i++) { int offset = (targets.length - 1 - i) * 8; targets[i] = (byte) ((s >>> offset) & 0xff); } return targets; } /** * long to byte[] * * @param s * long * @return byte[] * */ public static byte[] longToByteArray(long s) { byte[] targets = new byte[2]; for (int i = 0; i < 8; i++) { int offset = (targets.length - 1 - i) * 8; targets[i] = (byte) ((s >>> offset) & 0xff); } return targets; } /**32-bit int to byte[]*/ public static byte[] int2byte(int res) { byte[] targets = new byte[4]; targets[0] = (byte) (res & 0xff);// Lowest digit targets[1] = (byte) ((res >> 8) & 0xff);// Second low digit targets[2] = (byte) ((res >> 16) & 0xff);// The second high position targets[3] = (byte) (res >>> 24);// The highest position, unsigned right shift. return targets; } /** * Convert a byte array of length 2 into 16-bit int * * @param res * byte[] * @return int * */ public static int byte2int(byte[] res) { // res = InversionByte(res); // A byte data is shifted 24 bits left to 0x??000000, and then shifted 8 bits right to 0x00??00000 int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00); // | Indicates ambient or return targets; } }The above is the full content of the conversion implementation method of java byte array and int, long, short, byte brought to you. I hope everyone will support Wulin.com more~