Java CRC Calculate calculateCRC(String id)

Here you can find the source of calculateCRC(String id)

Description

calculate CRC

License

Open Source License

Declaration

public static int calculateCRC(String id) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    private static final int ID_LENGTH = 12;
    private static final int[][] CRC_WEIGHTS = new int[][] { new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 },
            new int[] { 3, 4, 5, 6, 7, 8, 9, 10, 11, 1, 2 }, };
    private static final int CRC_MODE = 11;
    private static final int CRC_INCORRECT = 10;

    public static int calculateCRC(String id) {
        if (id == null || id.length() < CRC_WEIGHTS[0].length || !isDigits(id)) {
            return -1;
        }//from  w  w  w  .j av a 2s.  c o m
        int crc = CRC_INCORRECT;
        int weightPos = 0;
        while (crc == CRC_INCORRECT && weightPos < CRC_WEIGHTS.length) {
            crc = 0;
            for (int i = 0; i < ID_LENGTH - 1; i++) {
                crc += charAsDigit(id.charAt(i)) * CRC_WEIGHTS[weightPos][i];
            }
            crc = crc % CRC_MODE;
            weightPos++;
        }
        return crc;
    }

    protected static boolean isDigits(String s) {
        for (char c : s.toCharArray()) {
            if (!Character.isDigit(c)) {
                return false;
            }
        }
        return true;
    }

    private static int charAsDigit(char c) {
        return Character.digit(c, 10);
    }
}

Related

  1. calcCRC(final byte[] data)
  2. calcCRC(int crc, byte[] bytes, int start, int len)
  3. calculateCRC(byte[] buff, int count)
  4. calculateCRC(byte[] data, int offset, int len)
  5. calculateCRC(String digitsToCheck)
  6. calculateCrc16(byte[] buffer)
  7. calculateCRC32(byte[] buf, int off, int len)
  8. computeCRC(InputStream in)
  9. computeCRC32(File file)