CRC32 Algorithm

The CRC32 algorithm, or Cyclic Redundancy Check 32-bit, is a widely-used error detection technique in computer networks and digital communication systems for ensuring data integrity. It is based on polynomial division and operates on binary data streams, generating a fixed-size checksum (32 bits) that is appended to the data before transmission. Upon receiving the data, the receiver can perform the same calculation and compare the resulting checksum with the one appended to the message. If the two checksums match, it is assumed that the data is error-free, while a mismatch indicates that the data has been altered or corrupted during transmission. The CRC32 algorithm is particularly efficient at detecting common errors such as single-bit errors, burst errors, and multiple-bit errors that are not too widely spread. This algorithm is a variation of the more general CRC family, which includes other bit-lengths such as CRC-8, CRC-16, and CRC-64. The algorithm's ability to detect errors is largely determined by the choice of the generator polynomial, which is a key parameter in the calculation of the checksum. CRC32 is widely used in various applications, such as Ethernet, ZIP and GZIP file formats, and data storage systems like hard drives, where data integrity is of utmost importance.
package Others;

import java.util.BitSet;

/**
 * Generates a crc32 checksum for a given string or byte array
 */
public class CRC32 {

    public static void main(String[] args) {
        System.out.println(Integer.toHexString(crc32("Hello World")));
    }

    public static int crc32(String str) {
        return crc32(str.getBytes());
    }

    public static int crc32(byte[] data) {
        BitSet bitSet = BitSet.valueOf(data);
        int crc32 = 0xFFFFFFFF; // initial value
        for (int i = 0; i < data.length * 8; i++) {
            if (((crc32 >>> 31) & 1) != (bitSet.get(i) ? 1 : 0))
                crc32 = (crc32 << 1) ^ 0x04C11DB7; // xor with polynomial
            else
                crc32 = (crc32 << 1);
        }
        crc32 = Integer.reverse(crc32); // result reflect
        return crc32 ^ 0xFFFFFFFF; // final xor value
    }

}

LANGUAGE:

DARK MODE: