最近做个通信项目使用UDP Socket,所以数据的接发都与byte[]有关,
基本类型与byte[]转换作为基础知识,需要mark一下. 0x0与0x00的区别是前者4位,后者8位.
ByteArrayOutputStream buf = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(buf);
out.writeShort(301);
byte[] b1 = buf.toByteArray();
for(byte bb : b1) {
System.out.print(Integer.toHexString(bb & 0xFF) + " ");
}
byte[] buf2 = {0x01,0x2d};
ByteArrayInputStream bintput = new ByteArrayInputStream(buf2);
DataInputStream dintput = new DataInputStream(bintput);
short i = dintput.readShort();
System.out.print(i);
//io的各种关闭省略..
如果把301定义成int,那么转换后byte[]的长度是4,内容是0x00 0x00 0x01 0x2d,因为int型占4byte32位,而short是2byte16位,同时注意取值范围.
public static int byte2ToUnsignedShort(byte[] bytes, int off) {
int high = bytes[off];
int low = bytes[off + 1];
return (high << 8 & 0xFF00) | (low & 0xFF);
}
public static byte[] unsignedShortToByte2(int s) {
byte[] targets = new byte[2];
targets[0] = (byte) (s >> 8 & 0xFF);
targets[1] = (byte) (s & 0xFF);
return targets;
}