package com.ruoyi.common.utils;

/**
 * TODO
 *
 * @author linfeng
 * @date 2022/12/8 16:04
 */
public class ModBusUtils {

    public static char byteToASCLL(byte b) {
        return (char) b;
    }


    /*
     * 字节数组转16进制字符串
     */
    public static String bytes2HexString(byte[] b) {
        String r = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            r += hex.toUpperCase() + " ";
        }
        return r;
    }
    public static byte[] hexStr2Bytes(String src) {
        src = src.replaceAll(" ", "");
        System.out.println(src);
        int m = 0, n = 0;
        int l = src.length() / 2;
        byte[] ret = new byte[l];
        for (int i = 0; i < l; i++) {
            m = i * 2 + 1;
            n = m + 1;
            String sss = "0x" + src.substring(i * 2, m) + src.substring(m, n);
            try {
                ret[i] = Byte.decode(sss);
            } catch (Exception e) {
                // TODO: handle exception
                int s = Integer.decode(sss);
                ret[i] = (byte)s;
            }
        }
        return ret;
    }
}

