这几天在做一个与PLC交互的系统,PLC会传过来一些指令,这些指令是二进制的格式,要转为4位十进制的指令来读,下面是代码部分:
public class BytesChange {
/**
* 二进制转十六进制方法
* @param bString
* @return
*/
public static String bytes2hex(String bString){
if(bString == null || bString.equals("") || bString.length() % 4 != 0){
return null;
}
int beginIndex = 0;
int length = 16;
String instructions = "";
while(true){
if((beginIndex+length)>bString.length()){
break;
}
String instruction = bString.substring(beginIndex, beginIndex + length);
String result = bytes2hex0f(instruction);
instructions += result + " ";
if("00ca".equals(result)){
break;
}
beginIndex += 16;
}
return instructions;
}
public static String bytes2hex0f(String bString){
StringBuffer sb = new StringBuffer();
int tmp = 0;
for(int i=0; i<bString.length(); i+=4){
tmp = 0;
for(int j=0;j<4;j++){
tmp += Integer.parseInt(bString.substring(i+j, i+j+1)) << (4-j-1);
}
sb.append(Integer.toHexString(tmp));
}
return sb.toString();
}
/**
* 十六进制转十进制
* @param strHex
* @return
*/
public static String hexToInt(String strHex){
int in = Integer.parseInt(strHex,16);
String result = "";
if(in < 10){
result = "0" + Integer.toString(in);
}else{
result = Integer.toString(in);
}
return result;
}
/**
* 测试
* @param args
*/
public static void main(String[] args) {
String message = "1010110000000000000000000000000100000000000000010000000000000001000000000000000100000000000000010000000011001010";
BytesChange bc = new BytesChange();
System.out.println(bc.bytes2hex(message));
String str = "0001";
System.out.println(bc.hexToInt(str));
}
}