/**
* Convert the base data type to a byte array, and the method of reverse conversion
* Only involves conversion operations, no validation for parameters
* Applicable scope: RMS operation, network data transmission
*/
Public class dataconvert{
/**
* Convert data of type int to byte array
* @param n int Data
* @return-generated byte array
*/
Public Static byte[] Inttobytes (int n) {
String s = string.valueof (n);
return s.getbytes ();
}
/**
* Converts a byte array to int data
* @param B-byte array
* @return the generated int data
*/
public static int bytestoint (byte[] b) {
string s = new string (b);
return Integer.parseint (s);
}
/**
* Convert data of type int to byte array
* Principle: four bytes in int data are taken out and stored separately
* @param n int Data
* @return-generated byte array
*/
Public Static byte[] IntToBytes2 (int n) {
byte[] b = new Byte[4];
for (int i = 0;i < 4;i++) {
B[i] = (byte) (n >> (24-i * 8));
}
return B;
}
/**
* Converts a byte array to int data
* @param B-byte array
* @return the generated int data
*/
public static int ByteToInt2 (byte[] b) {
return (((int) b[0]) << + (((int) b[1]) << + (((int) b[2]) << 8) + b[3];
}
}
How to convert int into byte[] in Android