Android CRC-CCITT



我需要一个CRC检查我写的应用程序,但不能找出在线代码和计算器我做错了什么。我可能只是没有正确理解。这就是我需要的:

它使用CRC-CCITT,起始值为0xFFFF,输入位顺序相反。例如,获取设备类型消息为:0x01, 0x06, 0x01, 0x00, 0x0B, 0xD9。CRC为0xD90B

这是我使用的代码:

public static int CRC16CCITT(byte[] bytes) {
    int crc = 0xFFFF;          // initial value
    int polynomial = 0x1021;   // 0001 0000 0010 0001  (0, 5, 12) 
    for (byte b : bytes) {
        for (int i = 0; i < 8; i++) {
            boolean bit = ((b   >> (7-i) & 1) == 1);
            boolean c15 = ((crc >> 15    & 1) == 1);
            crc <<= 1;
            if (c15 ^ bit) crc ^= polynomial;
         }
    }
    crc &= 0xffff;
    //System.out.println("CRC16-CCITT = " + Integer.toHexString(crc));
    return crc;

我是为Android设备写的,所以需要java。

这是我在我的应用程序中使用的代码(它工作)。

static public int GenerateChecksumCRC16(int bytes[]) {
        int crc = 0xFFFF;
        int temp;
        int crc_byte;
        for (int byte_index = 0; byte_index < bytes.length; byte_index++) {
            crc_byte = bytes[byte_index];
            for (int bit_index = 0; bit_index < 8; bit_index++) {
                temp = ((crc >> 15)) ^ ((crc_byte >> 7));
                crc <<= 1;
                crc &= 0xFFFF;
                if (temp > 0) {
                    crc ^= 0x1021;
                    crc &= 0xFFFF;
                }
                crc_byte <<=1;
                crc_byte &= 0xFF;
            }
        }
        return crc;
    }

帮助此链接https://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java

 /******************************************************************************
 *  Compilation:  javac CRC16CCITT.java
 *  Execution:    java CRC16CCITT s
 *  Dependencies: 
 *  
 *  Reads in a sequence of bytes and prints out its 16 bit
 *  Cylcic Redundancy Check (CRC-CCIIT 0xFFFF).
 *
 *  1 + x + x^5 + x^12 + x^16 is irreducible polynomial.
 *
 *  % java CRC16-CCITT 123456789
 *  CRC16-CCITT = 29b1
 *
 ******************************************************************************/
public class CRC16CCITT { 
    public static void main(String[] args) { 
        int crc = 0xFFFF;          // initial value
        int polynomial = 0x1021;   // 0001 0000 0010 0001  (0, 5, 12) 
        // byte[] testBytes = "123456789".getBytes("ASCII");
        byte[] bytes = args[0].getBytes();
        for (byte b : bytes) {
            for (int i = 0; i < 8; i++) {
                boolean bit = ((b   >> (7-i) & 1) == 1);
                boolean c15 = ((crc >> 15    & 1) == 1);
                crc <<= 1;
                if (c15 ^ bit) crc ^= polynomial;
            }
        }
        crc &= 0xffff;
        StdOut.println("CRC16-CCITT = " + Integer.toHexString(crc));
    }
}

最新更新