package com.yc.ship.module.trade.utils;

/**
 * CRC8算法生成校验码
 */
public class CCRC8Util {

    final static char[] digits = {
            '0', '1', '2', '3', '4', '5', '6', '7',
            '8','9', 'A', 'B', 'C', 'D', 'E', 'F',
            'G', 'H','J', 'K', 'L','M', 'N',  'P',
            'R', 'S', 'T', 'U', 'W', 'X', 'Y','Z' };

    /**
     *查找校验码
     * @param data
     * @return
     */
    public static long FindCRC(byte[] data){
        long CRC=0;
        long genPoly = 0Xaa;
        for(int i=0;i<data.length; i++){
            CRC ^= data[i];
            for(int j=0;j<8;j++){
                if((CRC & 0x80) != 0){
                    CRC = (CRC << 1) ^ genPoly;
                }else{
                    CRC <<= 1;
                }
            }
        }
        CRC &= 0xff;//保证CRC余码输出为2字节。
        return CRC;
    }

    /**
     * 进制转化
     * @param i 需要转化的值
     * @param system 进制
     * @return
     */
    public static String NumToStr(long i,int system) {
        long num = 0;
        if (i < 0) {
            num = ((long) 2 * 0x7fffffff) + i + 2;
        } else {
            num = i;
        }
        char[] buf = new char[32];
        int charPos = 32;
        while ((num / system) > 0) {
            buf[--charPos] = digits[(int) (num % system)];
            num /= system;
        }
        buf[--charPos] = digits[(int) (num % system)];
        return new String(buf, charPos, (32 - charPos));
    }
}
