java基础之short转换byte[]
最近做个通信项⽬使⽤UDP Socket,所以数据的接发都与byte[]有关,
基本类型与byte[]转换作为基础知识,需要mark⼀下. 0x0与0x00的区别是前者4位,后者8位.
ByteArrayOutputStream buf = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(buf);
out.writeShort(301);
字符串数组怎么转成bytebyte[] b1 = ByteArray();
for(byte bb : b1) {
System.out.HexString(bb & 0xFF) + " ");
}
byte[] buf2 = {0x01,0x2d};
ByteArrayInputStream bintput = new ByteArrayInputStream(buf2);
DataInputStream dintput = new DataInputStream(bintput);
short i = adShort();
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;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论