java 通讯报文 接口_Java对接硬件接口,采用Scoket连接,数据报文通信

public classHexUtil {public static byte[] hexStringToBytes(String hexString) {if (hexString == null || hexString.equals("")) {return null;

}//toUpperCase将字符串中的所有字符转换为大写

hexString =hexString.toUpperCase();int length = hexString.length() / 2;//toCharArray将此字符串转换为一个新的字符数组。

char[] hexChars =hexString.toCharArray();byte[] d = new byte[length];for (int i = 0; i < length; i++) {int pos = i * 2;

d[i]= (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));

}returnd;

}//charToByte返回在指定字符的第一个发生的字符串中的索引,即返回匹配字符

private static byte charToByte(charc) {return (byte) "0123456789ABCDEF".indexOf(c);

}public static String BinaryToHexString(byte[] bytes) {

String hexStr= "0123456789ABCDEF";

String result= "";

String hex= "";for (byteb : bytes) {

hex= String.valueOf(hexStr.charAt((b & 0xF0) >> 4));

hex+= String.valueOf(hexStr.charAt(b & 0x0F));

result+=hex ;

}returnresult;

}//两位一字符,倒序排序

public staticString reverseString(String str) {

List strlist=newArrayList();char[] chr =str.toCharArray();for (int i = 0 ; i < chr.length; i=i+2) {

String s=chr[i]+""+chr[i+1];

strlist.add(s);

}

Collections.reverse(strlist);

String result="";for(String v:strlist){

result+=v;

}returnresult;

}/*** 16进制转换成为string类型字符串

*@params

*@return

*/

public staticString hexStringToString(String s) {if (s == null || s.equals("")) {return null;

}

s= s.replace(" ", "");byte[] baKeyword = new byte[s.length() / 2];for (int i = 0; i < baKeyword.length; i++) {try{

baKeyword[i]= (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));

}catch(Exception e) {

e.printStackTrace();

}

}try{

s= new String(baKeyword, "UTF-8");newString();

}catch(Exception e1) {

e1.printStackTrace();

}returns;

}/*** 字符串转化成为16进制字符串

*@params

*@return

*/

public staticString strTo16(String s) {

String str= "";for (int i = 0; i < s.length(); i++) {int ch = (int) s.charAt(i);

String s4=Integer.toHexString(ch);

str= str +s4;

}returnstr;

}//将16进制字符串自动补全到8位 并且倒序排序

public staticString full8(String lenth) {int a =lenth.getBytes().length;int b = 8 -a;for (int i = 0; i < b; i++) {

lenth= "0" +lenth;

}returnreverseString(lenth);

}/*** xor运算

*

*@paramdata

*@return

*/

public static String getBCC(byte[] data) {

String ret= "";byte BCC[] = new byte[1];for (int i = 0; i < data.length; i++) {

BCC[0] = (byte) (BCC[0] ^data[i]);

}

String hex= Integer.toHexString(BCC[0] & 0xFF);if (hex.length() == 1) {

hex= '0' +hex;

}

ret+=hex.toUpperCase();returnret;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值