Bootstrap

【JMeter 菜鸟实操之六】beanshell中处理16进制字符方法收集(物联网常用)

//将int字符串转为16进制字符串
String hex = Integer.toHexString(Integer.valueOf(“123”));

//将Long字符串转为16进制字符串
String hex = Long.toHexString(Long.valueOf(“0123456789”));

//将float转为16进制字符串
String hex = Integer.toHexString(Float.floatToIntBits(10.10));

 
//将含字母或符号的字符串转为16进制(ASCII码转十六进制)
public String convertStringToHex(String str){
     char[] chars = str.toCharArray();
     StringBuffer hex = new StringBuffer();
     for(int i = 0; i < chars.length; i++)
     {
         hex.append(Integer.toHexString((int)chars[i]));
     }
     return hex.toString();
}

//将16进制转为含字母或符号的字符串(十六进制转ASCII码)
public String convertHexToString(String hex){
	  StringBuilder sb = new StringBuilder();
	  StringBuilder temp = new StringBuilder();
	  for( int i=0; i<hex.length()-1; i+=2 ){
	      //grab the hex in pairs
	      String output = hex.substring(i, (i + 2));
	      //convert hex to decimal
	      int decimal = Integer.parseInt(output, 16);
	      //convert the decimal to character
	      sb.append((char)decimal); 
	      temp.append(decimal);
	  } 
	  return sb.toString();
	  }

 
//将16进制字符串转为xx字节16进制字符串,不足位数,前面补0
public static String add_zore(String str, int size){
        if (str.length()<size){
            str= "0" + str;
            str= add_zore(str,size);
            return str;
        }else {
            return str;
        }
}

 
 //将16进制数据,转为小端模式(低位转为高位)
 public static String reverseHex(String hex) {
        char[] charArray = hex.toCharArray();
        int length = charArray.length;
        int times = length / 2;
        for(int c1i = 0; c1i < times; c1i += 2) {
             int c2i = c1i + 1;
             char c1 = charArray[c1i];
             char c2 = charArray[c2i];
             int c3i = length - c1i - 2;
             int c4i = length - c1i - 1;
             charArray[c1i] = charArray[c3i];
             charArray[c2i] = charArray[c4i];
             charArray[c3i] = c1;
             charArray[c4i] = c2;
        }
        return new String(charArray);
}

  
//从响应值中,截取xx位,并将截取的16进制字符串转为10进制字符串
String time = response.substring(62, 74);
log.info("time_16:"+ time);
long time_10 = Long.parseLong(time, 16);
或
String time_10 = String.valueOf(Long.valueOf(time, 16));
log.info("time_10:"+ time_10);

//16进制float转10进制
Float value = Float.intBitsToFloat(Integer.valueOf(test.trim(), 16));
log.info("value:"+ value);

 

;