黄磊的项目,分享文件
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

78 lines
2.3 KiB

package com.github.wxiaoqi.security.common.util;
import java.util.Arrays;
/**
* Created by huangchongguo on 2020/7/1.
* Description:No
*/
public class BytesUtil {
/*public static <R> R RgetClassObject(Object classObject, byte[] bytes){
bytes=getContentByBytes(bytes);
Class<?> []classZ=new Class[]{classObject.getClass()};
return (R)InvokeMethodOpen.invokeMethod(classObject.getClass(),classObject,"parseFrom",classZ,bytes);
}*/
//获取类型(ClassType)
public static int getClassTypeByBytes(byte[] bytes){
return BytesUtil.bytes2Int(Arrays.copyOfRange(bytes,0,4));
}
//获取内容(payload)
public static byte[] getContentByBytes(byte[] bytes){
if (bytes.length<=3){
throw new RuntimeException("getContentByBytes length is short");
}
return Arrays.copyOfRange(bytes,4,bytes.length);
}
//融合classType和实际内容
public static byte[] typeAndPayloadMerger(byte[] bt1,byte[] bt2){
//byte[] bt1=BytesUtil.int2Bytes(classType.getType());//classType
byte[] bt3 = new byte[bt1.length+bt2.length];
System.arraycopy(bt1, 0, bt3, 0, bt1.length);
System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
return bt3;
}
public static int bytes2Int(byte[] bytes) {
int result = 0;
//将每个byte依次搬运到int相应的位置
result = bytes[0] & 0xff;
result = result << 8 | bytes[1] & 0xff;
result = result << 8 | bytes[2] & 0xff;
result = result << 8 | bytes[3] & 0xff;
return result;
}
public static byte[] int2Bytes(int num) {
byte[] bytes = new byte[4];
//通过移位运算,截取低8位的方式,将int保存到byte数组
bytes[0] = (byte)(num >>> 24);
bytes[1] = (byte)(num >>> 16);
bytes[2] = (byte)(num >>> 8);
bytes[3] = (byte)num;
return bytes;
}
public static Byte[] byte2Byte(byte[] bytesPrim) {
Byte[] bytes = new Byte[bytesPrim.length];
int i = 0;
for (byte b : bytesPrim) bytes[i++] = b; // Autoboxing
return bytes;
}
public static byte[] Byte2Byte(Byte[] bytesPrim) {
byte[] bytes = new byte[bytesPrim.length];
int i = 0;
for (Byte b : bytesPrim) bytes[i++] = b; // Autoboxing
return bytes;
}
}