package com.mindprod.example;

import sun.misc.CRC16;

import java.io.UnsupportedEncodingException;

/**
 * 16-bit unofficial Sun CRC, cyclic redundancy checks.
 * <p/>
 * composed with IntelliJ IDEA
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0
 */
public final class TestSunCRC16
    {
    // -------------------------- STATIC METHODS --------------------------

    /**
     * Calc CRC-16 with unofficial Sun method. You will get a warning message of the form
     * [warning: sun.misc.CRC16 is Sun proprietary API and may be removed in a future release]
     *
     * @param ba byte array to compute CRC on
     * @return 16-bit CRC, signed
     */
    private static short sunCRC16( byte[] ba )
        {
        // create a new CRC-calculating object
        final CRC16 crc = new CRC16();
        // loop, calculating CRC for each byte of the string
        // There is no CRC16.update(byte[]) method.
        for ( byte b : ba )
            {
            crc.update( b );
            }
        // note use crc.value, not crc.getValue()
        return ( short ) crc.value;
        }

    // --------------------------- main() method ---------------------------

    /**
     * Test harness
     *
     * @param args not used
     * @throws java.io.UnsupportedEncodingException
     *          in case UTF-8 support missing.
     */
    public static void main( String[] args ) throws UnsupportedEncodingException
        {
        final String s = "The quick brown fox jumped over the lazy dog's back";
        final byte[] ba = s.getBytes( "UTF-8"/* encoding */ );
        System.out.println( sunCRC16( ba ) );
        }
    }