问题1:java中没有实现这种“byte a = 0xB2 --> String b = “B2””转换的简单实现需要自己实现。
答:自己编写的转换函数,思路将byte的高低4位分开,分别转换为对应的字符然后合成返回的字符串。
public static String byteToString(byte b) {
byte high, low;
byte maskHigh = (byte)0xf0;
byte maskLow = 0x0f;
high = (byte)((b & maskHigh) >> 4);
low = (byte)(b & maskLow);
StringBuffer buf = new StringBuffer();
buf.append(findHex(high));
buf.append(findHex(low));
return buf.toString();
}
private static char findHex(byte b) {
int t = new Byte(b).intValue();
t = t < 0 ? t + 16 : t;
if ((0 <= t) &&(t <= 9)) {
return (char)(t + '0');
}
return (char)(t-10+'A');
}
未解决的疑问在java中不存在类似C中的无符号量,所以如果一个字节超过0x80其对应的整型值即为负值,但在高位右移4位后还是负值,且与对应的正值相差16,比如0xB2经过右移后的期望值是0x0B(11)但实际值是-5与预期的值相差16(这个16通过多次试验得出),对此现象为找到合理的解释。
问题2:“String a=”B2” --> byte b=0xB2”字符的byte转换为byte数据类型
答:思路通过Integer作为转换的中间桥梁
public static int stringToByte(String in, byte[] b) throws Exception {
if (b.length < in.length() / 2) {
throw new Exception("byte array too small");
}
int j=0;
StringBuffer buf = new StringBuffer(2);
for (int i=0; i<in.length(); i++, j++) {
buf.insert(0, in.charAt(i));
buf.insert(1, in.charAt(i+1));
int t = Integer.parseInt(buf.toString(),16);
System.out.println("byte hex value:" + t);
b[j] = (byte)t;
i++;
buf.delete(0,2);
}
return j;
}
问题3:整数(表示范围限定为两个字节unsigned short)通过Integer.byteValue()转换成byte[2],如果超出一个byte的表示范围将会截断高位的值。
答:思路一个byte能表示的最大整数为256(超过128为负值,超过256将被截断),所以取256的倍数为byte[0],256的余数为byte[1]。
byte[] d = new byte[l+2];
….
buff.put(new Integer(l/256).byteValue());
buff.put(new Integer(l%256).byteValue());
地址:http://blog.csdn.net/dynamo2/archive/2005/08/30/468105.aspx
评论:管用
自己代码:
package test;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.SerializationUtils;
public class SerialTest {
}
运行结果:
ACED0005737200116A617661
{2=cde, 1=test.SeriaTestClass@b76fa}
{2=cde, 1=test.SeriaTestClass@177b3cd}
false
false
说明:由于内部SeriaTestClass也被序列化,所以两个对象不同