java short转byte_java基础之short转换byte[]
最近做個通信項目使用UDP Socket,所以數(shù)據(jù)的接發(fā)都與byte[]有關(guān),
基本類型與byte[]轉(zhuǎn)換作為基礎(chǔ)知識,需要mark一下.?0x0與0x00的區(qū)別是前者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的各種關(guān)閉省略..
如果把301定義成int,那么轉(zhuǎn)換后byte[]的長度是4,內(nèi)容是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;
}
總結(jié)
以上是生活随笔為你收集整理的java short转byte_java基础之short转换byte[]的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 关于iReport中纸张的大小 换算
 - 下一篇: Google Cloud + Fireb