package com.cisdi.data.HJ212.gateway;

import java.nio.charset.Charset;

public class CRC16Util {
    public static final Charset UTF8 = Charset.forName("UTF-8");
    
    /**
     * HJ212污染监测 CRC16校验算法
     * 
     * @param dataBody
     * @return CRC16校验码
     */
    public static String CRC16(String dataBody) {
        Integer[] regs = new Integer[dataBody.length()];
        for (int i = 0; i < dataBody.length(); i++) {
            regs[i] = (int)dataBody.charAt(i);
        }
        int por = 0xFFFF;
        for (int j = 0; j < regs.length; j++) {
            por = por >> 8;
            por ^= regs[j];
            for (int i = 0; i < 8; i++) {
                if ((por & 0x01) == 1) {
                    por = por >> 1;
                    por = por ^ 0xa001;
                } else
                    por = por >> 1;
            }
        }
        String result = Integer.toHexString(por).toUpperCase();
        
        while (result.length() < 4) {
            result = "0" + result;
            
        }
        return result;
    }

    public static void main(String[] args) {
        String body1 =
            "QN=20160801085857223;ST=32;CN=1062;PW=100000;MN=010000A8900016F000169DC0;Flag=5;CP=&&RtdInterval=30&&";
        System.out.println(CRC16(body1)); // should be 1C80

        String body2 = "QN=20120416225111069;ST=91;CN=9021;PW=122333;MN=88888880000006;Flag=1;CP=&&&&";
        System.out.println(CRC16(body2)); // should be 4100
    }
}
