CRC计算的Java代码

问题描述 投票:0回答:2

我已经有在 Java 中计算 CRC-8、CRC-16、CRC-32 的工作示例,但它们是不同的实现,我有点困惑。我尝试阅读数学技术文档,但对于我的数学水平来说似乎有点太多了。此外,从 C/C++ 转换代码并不那么简单,因为 Java 不能很好地处理无符号基元...

我需要一个完整的示例来理解并能够验证我的校验和,因为那里有很多不同的多项式!

请参阅 Philip Koopman 的最佳 CRC 多项式Philip Koopman 的 CRC Hamming 权重数据

如果有人可以提供一个最小但详细的 Java 示例,例如CRC-8,确实:

  1. 计算字节数组的校验和(没有查找表)。
  2. 以编程方式创建 crc 查找表。
  3. 使用查找表计算字节数组的校验和。
java checksum crc
2个回答
1
投票

这就是我为 CRC-8 所做的整理。尽管如此,我仍然无法完全理解多项式是如何产生的,特别是为什么我们应该/可以使用相反的版本!我还错过了 CRC-16、CRC-32,也许还有 CRC-64 完整示例,如下所示。希望将来有人能满足这个需求。

此代码使用

polynomial: 0xa6 = x^8 + x^6 + x^3 + x^2 + 1  (0x14d) <=> (0xb2; 0x165)
,如 Mark Adler 建议的那样,并基于 基于这些测试,显示了该多项式的强度。

import java.io.UnsupportedEncodingException;

/**
 * Calculate CRC8 based on a lookup table.
 * CRC-8     : CRC-8K/3 (HD=3, 247 bits max)
 * polynomial: 0xa6 = x^8 + x^6 + x^3 + x^2 + 1  (0x14d) <=> (0xb2; 0x165)
 * init = 0
 *
 * There are two ways to define a CRC, forward or reversed bits.
 * The implementations of CRCs very frequently use the reversed bits convention,
 * which this one does. 0xb2 is 0x4d reversed. The other common convention is
 * to invert all of the bits of the CRC, which avoids a sequence of zeros on
 * a zero CRC resulting in a zero CRC. The code below does that as well.
 *
 * usage:
 * new Crc8().update("123456789").getHex() == "D8"
 * new Crc8().update("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").getHex() == "EF"
 */
public final class Crc8 {

    private static final short CRC8_POLYNOMIAL = 0xB2;
    public static short[] createLookupTable()
    {
        short[] lookupTable = new short[256];
        for(int i=0; i<256; i++)
        {
            int rem = i; // remainder from polynomial division
            for(int j=0; j<8; j++)
            {
                if((rem & 1) == 1)
                {
                    rem >>= 1;
                    rem ^= CRC8_POLYNOMIAL;
                }
                else
                {
                    rem >>= 1;
                }
            }
            lookupTable[i] = (short)rem;
        }
        return( lookupTable );
    }

    private static final short CRC8_INIT_VALUE = 0xFF;
    private static final short[] CRC8_LOOKUP_TABLE = {
        0x00, 0x3E, 0x7C, 0x42, 0xF8, 0xC6, 0x84, 0xBA,
        0x95, 0xAB, 0xE9, 0xD7, 0x6D, 0x53, 0x11, 0x2F,
        0x4F, 0x71, 0x33, 0x0D, 0xB7, 0x89, 0xCB, 0xF5,
        0xDA, 0xE4, 0xA6, 0x98, 0x22, 0x1C, 0x5E, 0x60,
        0x9E, 0xA0, 0xE2, 0xDC, 0x66, 0x58, 0x1A, 0x24,
        0x0B, 0x35, 0x77, 0x49, 0xF3, 0xCD, 0x8F, 0xB1,
        0xD1, 0xEF, 0xAD, 0x93, 0x29, 0x17, 0x55, 0x6B,
        0x44, 0x7A, 0x38, 0x06, 0xBC, 0x82, 0xC0, 0xFE,
        0x59, 0x67, 0x25, 0x1B, 0xA1, 0x9F, 0xDD, 0xE3,
        0xCC, 0xF2, 0xB0, 0x8E, 0x34, 0x0A, 0x48, 0x76,
        0x16, 0x28, 0x6A, 0x54, 0xEE, 0xD0, 0x92, 0xAC,
        0x83, 0xBD, 0xFF, 0xC1, 0x7B, 0x45, 0x07, 0x39,
        0xC7, 0xF9, 0xBB, 0x85, 0x3F, 0x01, 0x43, 0x7D,
        0x52, 0x6C, 0x2E, 0x10, 0xAA, 0x94, 0xD6, 0xE8,
        0x88, 0xB6, 0xF4, 0xCA, 0x70, 0x4E, 0x0C, 0x32,
        0x1D, 0x23, 0x61, 0x5F, 0xE5, 0xDB, 0x99, 0xA7,
        0xB2, 0x8C, 0xCE, 0xF0, 0x4A, 0x74, 0x36, 0x08,
        0x27, 0x19, 0x5B, 0x65, 0xDF, 0xE1, 0xA3, 0x9D,
        0xFD, 0xC3, 0x81, 0xBF, 0x05, 0x3B, 0x79, 0x47,
        0x68, 0x56, 0x14, 0x2A, 0x90, 0xAE, 0xEC, 0xD2,
        0x2C, 0x12, 0x50, 0x6E, 0xD4, 0xEA, 0xA8, 0x96,
        0xB9, 0x87, 0xC5, 0xFB, 0x41, 0x7F, 0x3D, 0x03,
        0x63, 0x5D, 0x1F, 0x21, 0x9B, 0xA5, 0xE7, 0xD9,
        0xF6, 0xC8, 0x8A, 0xB4, 0x0E, 0x30, 0x72, 0x4C,
        0xEB, 0xD5, 0x97, 0xA9, 0x13, 0x2D, 0x6F, 0x51,
        0x7E, 0x40, 0x02, 0x3C, 0x86, 0xB8, 0xFA, 0xC4,
        0xA4, 0x9A, 0xD8, 0xE6, 0x5C, 0x62, 0x20, 0x1E,
        0x31, 0x0F, 0x4D, 0x73, 0xC9, 0xF7, 0xB5, 0x8B,
        0x75, 0x4B, 0x09, 0x37, 0x8D, 0xB3, 0xF1, 0xCF,
        0xE0, 0xDE, 0x9C, 0xA2, 0x18, 0x26, 0x64, 0x5A,
        0x3A, 0x04, 0x46, 0x78, 0xC2, 0xFC, 0xBE, 0x80,
        0xAF, 0x91, 0xD3, 0xED, 0x57, 0x69, 0x2B, 0x15
    };

    private final boolean useLookupTable;
    private short crc8;


    public Crc8()
    {
        this(true);
    }


    public Crc8(boolean use_lookup_table)
    {
        useLookupTable = use_lookup_table;
        reset();
    }


    public Crc8 reset()
    {
        crc8 = CRC8_INIT_VALUE;
        return( this );
    }


    public Crc8 update(byte b)
    {
        if( useLookupTable )
        {
            crc8 = CRC8_LOOKUP_TABLE[(crc8 ^ b) & 0xFF];
        }
        else
        {
            crc8 ^= b;
            crc8 &= 0xFF;
            for(int j=0; j<8; j++)
            {
                if((crc8 & 1) == 1)
                {
                    crc8 >>= 1;
                    crc8 ^= CRC8_POLYNOMIAL;
                }
                else
                {
                    crc8 >>= 1;
                }
            }
        }
        return( this );
    }


    public Crc8 update(byte[] data, int offset, int length)
    {
        for(int i=offset; i < length; i++)
        {
            update( data[i] );
        }
        return( this );
    }


    public Crc8 update(byte[] data)
    {
        return update(data, 0, data.length);
    }


    public Crc8 update(String s)
    {
        try
        {
            return update(s.getBytes("UTF-8"));
        }
        catch(UnsupportedEncodingException ex)
        {
            throw new RuntimeException(ex);
        }
    }


    public short get()
    {
        return( (short)(crc8 ^ 0xFF) );
    }


    /**
     * Return calculated CRC8 in 2 capital hex digits with leading zeros.
     */
    public String getHex()
    {
        return( String.format("%02X", get()) );
    }

}

0
投票

//实现该方法的Java代码

导入java.util.Arrays;

课程计划{

// Returns XOR of 'a' and 'b'

// (both of same length)

static String Xor(String a, String b)

{


    // Initialize result

    String result = "";

    int n = b.length();


    // Traverse all bits, if bits are

    // same, then XOR is 0, else 1

    for (int i = 1; i < n; i++) {

        if (a.charAt(i) == b.charAt(i))

            result += "0";

        else

            result += "1";

    }

    return result;

}


// Performs Modulo-2 division

static String Mod2Div(String dividend, String divisor)

{


    // Number of bits to be XORed at a time.

    int pick = divisor.length();


    // Slicing the dividend to appropriate

    // length for particular step

    String tmp = dividend.substring(0, pick);


    int n = dividend.length();


    while (pick < n) {

        if (tmp.charAt(0) == '1')


            // Replace the dividend by the result

            // of XOR and pull 1 bit down

            tmp = Xor(divisor, tmp)

                  + dividend.charAt(pick);

        else


            // If leftmost bit is '0'.

            // If the leftmost bit of the dividend (or

            // the part used in each step) is 0, the

            // step cannot use the regular divisor; we

            // need to use an all-0s divisor.

            tmp = Xor(new String(new char[pick])

                          .replace("\0", "0"),

                      tmp)

                  + dividend.charAt(pick);


        // Increment pick to move further

        pick += 1;

    }


    // For the last n bits, we have to carry it out

    // normally as increased value of pick will cause

    // Index Out of Bounds.

    if (tmp.charAt(0) == '1')

        tmp = Xor(divisor, tmp);

    else

        tmp = Xor(new String(new char[pick])

                      .replace("\0", "0"),

                  tmp);


    return tmp;

}


// Function used at the sender side to encode

// data by appending remainder of modular division

// at the end of data.

static void EncodeData(String data, String key)

{

    int l_key = key.length();


    // Appends n-1 zeroes at end of data

    String appended_data

        = (data

           + new String(new char[l_key - 1])

                 .replace("\0", "0"));


    String remainder = Mod2Div(appended_data, key);


    // Append remainder in the original data

    String codeword = data + remainder;

    System.out.println("Remainder : " + remainder);

    System.out.println(

        "Encoded Data (Data + Remainder) :" + codeword

        + "\n");

}


// checking if the message received by receiver is

// correct or not. If the remainder is all 0 then it is

// correct, else wrong.

static void Receiver(String data, String key)

{

    String currxor

        = Mod2Div(data.substring(0, key.length()), key);

    int curr = key.length();

    while (curr != data.length()) {

        if (currxor.length() != key.length()) {

            currxor += data.charAt(curr++);

        }

        else {

            currxor = Mod2Div(currxor, key);

        }

    }

    if (currxor.length() == key.length()) {

        currxor = Mod2Div(currxor, key);

    }

    if (currxor.contains("1")) {

        System.out.println(

            "there is some error in data");

    }

    else {

        System.out.println("correct message received");

    }

}


// Driver code

public static void main(String[] args)

{

    String data = "100100";

    String key = "1101";

    System.out.println("\nSender side...");

    EncodeData(data, key);


    System.out.println("Receiver side...");

    Receiver(data+Mod2Div(data+new String(new char[key.length() - 1])

                          .replace("\0", "0"),key),key);

}

}

//此代码由phasing17贡献

© www.soinside.com 2019 - 2024. All rights reserved.