java基礎之short轉換byte[]


最近做個通信項目使用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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM