定义字节工具(用于解析/编码基本对象)
package com.net.tcp;
import java.io.UnsupportedEncodingException;
/**
*
* 字节工具类
*
*/
public class ByteUtils {
public static byte[] getBytes(Object o){
int len = DataType.getLenByObject(o);
if(len > 0){
byte[] bytes = new byte[len];
if(o instanceof Number){
long value = 0;
if(o instanceof Float){
value = Float.floatToIntBits((Float)o);
}else if(o instanceof Double){
value = Double.doubleToLongBits((Double)o);
}else{
value = ((Number)o).longValue();
}
for(int i = 0; i < len; i++){
bytes[i] = (byte)((value >> ((len - i - 1) * 8)) & 0x00ff);
}
}else if(o instanceof Boolean){
bytes[0] = ((Boolean)o) ? (byte)1 : (byte)0;
}
return bytes;
}else if(o instanceof String){
try {
return ((String)o).getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return new byte[0];
}
public static Object getObject(byte[] bytes, short type){
if(DataType.isNumberByType(type)){
long value = 0l;
int len = DataType.getLenByType(type);
for(int i = 0; i < len; i++){
value += ((long)(bytes[i] & 0x00ff)) << ((len - i - 1) * 8);
}
switch(type){
case DataType.TYPE_BYTE:
return (byte)value;
case DataType.TYPE_SHORT:
return (short)value;
case DataType.TYPE_INT:
return (int)value;
case DataType.TYPE_DOUBLE:
return Double.longBitsToDouble(value);
}
}else if(type == DataType.TYPE_STRING){
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}else if(type == DataType.TYPE_BOOL){
return bytes[0] == 1;
}else{
throw new RuntimeException("无法解析类型...");
}
return null;
}
}