package com.jiayue.ipfcst.fileupload.util;

import java.util.ArrayList;
import java.util.List;

/**
 * 102工具类
 *
 * @author xsl
 * @version 3.0
 */
public class IEC102Uitl {
  /**
   * 取得是低位校验和
   *
   * @param data 需要计算校验和的16进制串
   * @return 校验和
   */
  public static String makeChecksum(String data) {
    int iTotal = 0;
    int iLen = data.length();
    int iNum = 0;

    while (iNum < iLen) {
      String s = data.substring(iNum, iNum + 2);
      iTotal += Integer.parseInt(s, 16);
      iNum = iNum + 2;
    }

    /**
     * 用256求余最大是255，即16进制的FF
     */
    int iMod = iTotal % 256;
    String sHex = Integer.toHexString(iMod);
    iLen = sHex.length();
    //如果不够校验位的长度，补0,这里用的是两位校验
    if (iLen < 2) {
      sHex = "0" + sHex;
    }
    return sHex;
  }

  /**
   * 将字符串每2个放到一个数组中
   *
   * @param str
   * @return
   */
  public static String[] stingToArray(String str) {
    int m = str.length() / 2;
    if (m * 2 < str.length()) {
      m++;
    }
    String[] strs = new String[m];
    int j = 0;
    for (int i = 0; i < str.length(); i++) {
      if (i % 2 == 0) {//每隔两zd个
        strs[j] = "" + str.charAt(i);
      } else {
        strs[j] = strs[j] + str.charAt(i);//将字符加上两个空格
        j++;
      }
    }
    return strs;
  }

  /**
   * 空格分割符字符串
   * 每两位添加一个空格分隔符
   *
   * @param str str
   * @return string
   */
  public static String delimiterStringBySpace(String str) {
    if (str == null || "".equals(str.trim())) {
      return null;
    }
    String regex = "(.{2})";
    String result = str.replaceAll(regex, "$1 ");
    return result;
  }

  public static List<String> stingToList(String str) {
    List<String> list = new ArrayList<String>();
    int m = str.length() / 2;
    if (m * 2 < str.length()) {
      m++;
    }
    int j = 0;
    for (int i = 0; i < str.length(); i++) {
      if (i % 2 == 0) {//每隔两zd个
        list.add("" + str.charAt(i)+str.charAt(i+1));
      } else {
        j++;
      }
    }
    return list;
  }
}
