赞
踩
解析:
首先是读取字节:
/*** 读取输入流中指定字节的长度
*
* 输入流
*
*@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"));
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。