解析:
首先是讀取字節:
/*** 讀取輸入流中指定字節的長度
*
* 輸入流
*
*@paramlength 指定長度
*@return指定長度的字節數組*/
public static byte[] readBytesFromTo(byte[] buffer, int from, intlength) {byte[] sub = new byte[length];int cur = 0;for (int i = from; i < length + from; i++) {
sub[cur]=buffer[i];
cur++;
}returnsub;
}
讀取之后轉為字符串或者整型:
/*** byte[]轉int
*
*@parambytes 報文
*@returnInteger*/
public static int byteArrayToInt(byte[] bytes) {int value = 0;//由高位到低位
for (int i = 0; i < 4; i++) {int shift = (4 - 1 - i) * 8;
value+= (bytes[i] & 0x000000FF) << shift;//往高位游
}returnvalue;
}/*** 字節轉字符串
*@parambytes 報文*/
public static String byteArrayToString(byte[] bytes,int start , int end){return newString(bytes, start, end);
}
發送報文:
將java類型轉化為二進制:
/***@parami
*@return
*/
public static byte[] intToByteArray(inti) {byte[] result = new byte[4];
result[0] = (byte) ((i >> 24) & 0xFF);
result[1] = (byte) ((i >> 16) & 0xFF);
result[2] = (byte) ((i >> 8) & 0xFF);
result[3] = (byte) (i & 0xFF);returnresult;
}/***
*@params
*@return
*/
public static byte[] StringToByteArray(String s) {returns.getBytes();
}
整合二進制數組:
/***
*@parambytes
*@return
*/
public static byte[] combineByte(byte[] ... bytes){int length = 0;for (byte[] b : bytes) {
length+=b.length;
}byte[] allByte=new byte[length];int positon=0;for (byte[] b : bytes) {
System.arraycopy(b,0, allByte, positon, b.length);
positon+=b.length;
}returnallByte;
}
求校驗和:
/***
*@paraminput
*@return
*/
public static int getCheckSum(byte[]... input) {int re = 0;for (byte[] b : input) {for (byteaB : b) {
re+= aB & 0x0FF;//注意此處要轉化為無符號
}
}returnre;
}
二進制內容有時候要在不同的環境下解析和發送,下面是C++和java的字符差異
下面給出在不同字符集編碼下的字節數:
英文字母:
字節數 : 1;編碼:GB2312 ? ? ? ? ? ? 字節數: 1;編碼:GBK??????????? 字節數 : 1;編碼:GB18030
字節數 : 1;編碼:ISO-8859-1 ? ? ? ?字節數: 1;編碼:UTF-8???????? 字節數 : 4;編碼:UTF-16
字節數 : 2;編碼:UTF-16BE?????????? 字節數: 2;編碼:UTF-16LE
中文漢字:
字節數 : 2;編碼:GB2312????????????? 字節數: 2;編碼:GBK??????????? 字節數 : 2;編碼:GB18030
字節數 : 1;編碼:ISO-8859-1??????? 字節數: 3;編碼:UTF-8???????? 字節數 : 4;編碼:UTF-16
字節數 : 2;編碼:UTF-16BE?????????? 字節數: 2;編碼:UTF-16LE
編碼不同會影響解析的方式的差異,有時候還是蠻頭疼的,比如我們常用的中文問題,C++默認用GB2312編碼,所以java的解析要變一下:
String describe = new String(bytes, start += 4, describeLength, Charset.forName("GB2312"));