public class ByteConvert {
/**
* 整型转化为字节数组
* @param id
* @return
*/
public byte[] int2Byte(int id){
byte[] arr=new byte[4];
for(int i=0;i<4;i++){
arr[i]=(byte)((id>>i*8)&0xff);
}
return arr;
}
/*
* 字节数组转化为整型
*/
public int byte2Int(byte[] arr){
int count=0;
for(int i=0;i<4;i++){
int add=(int)((arr[i]&0xff)<<(i*8));
count+=add;
}
return count;
}
//long型转化为byte[]
public byte[] long2Byte(long id){
byte[] arr=new byte[8];
for(int i=0;i<arr.length;i++){
arr[i]=(byte)((id>>i*8)&0xff);
}
return arr;
}
//byte[]转化为long
public long byte2long(byte[] arr){
long result=0;
for(int i=0;i<arr.length;i++){
long add=(long)((arr[i]&0xff)<<i*8);
result+=add;
}
return result;
}
public static void main(String[] args) {
ByteConvert bc=new ByteConvert();
//int转化为byte[]
byte[] arr=bc.int2Byte(8143);
for(byte one:arr){
System.out.println(one);
}
//测试从字节数组转化为整型
System.out.println(bc.byte2Int(arr));
//long转化为byte[]
byte[] arr2=bc.long2Byte(8143);
for(byte one:arr2){
System.out.println(one);
}
//byte[]转化为long
System.out.println(bc.byte2long(arr2));
//String转化为byte[]
String str="我是lcc";
byte[] arr3=str.getBytes();
//byte[]转化为String
String str2=new String(arr3);
System.out.println(str2);
}
运行结果:
-49
31
0
0
8143
-49
31
0
0
0
0
0
0
8143
我是lcc