Java Exercises: Generate a crc32 checksum of a given string or byte array

Java Basic: Exercise-250 with Solution

From Wikipedia - A cyclic redundancy check (CRC) is an error-detecting code commonly used in digital networks and storage devices to detect accidental changes to raw data. Blocks of data entering these systems get a short check value attached, based on the remainder of a polynomial division of their contents. On retrieval, the calculation is repeated and, in the event the check values do not match, corrective action can be taken against data corruption. CRCs can be used for error correction.
Write a Java program to generate a crc32 checksum of a given string or byte array?

Sample Solution:

Java Code:

import java.util.Scanner;
import java.util.BitSet;

public class solution {
    public static int convert_crc32(byte[] data) {
        BitSet bitSet = BitSet.valueOf(data);
        int crc32 = 0xFFFFFFFF; 
        for (int i = 0; i < data.length * 8; i++) {
            if (((crc32 >>> 31) & 1) != (bitSet.get(i) ? 1 : 0))
                crc32 = (crc32 << 1) ^ 0x04C11DB7;  
                crc32 = (crc32 << 1);
        crc32 = Integer.reverse(crc32);  
        return crc32 ^ 0xFFFFFFFF;  
   public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Input a string: ");
		String str1 = scanner.nextLine();
		System.out.println("crc32 checksum of the string: "+Integer.toHexString(convert_crc32(str1.getBytes())));		

Sample Output:

Input a string:  The quick brown fox
crc32 checksum of the string: b74574de


Flowchart: Generate a crc32 checksum of a given string or byte array.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to count the number of set bits in a 32-bit integer.
Next: Java Data Types Exercises

What is the difficulty level of this exercise?

Java: Tips of the Day

Parsing dates:

import java.io.*;
import java.util.*;
import java.text.*;

String s = "2001/09/23 14:39";

SimpleDateFormat formatter = new SimpleDateFormat ("yyyy/MM/dd H:mm");
Date d = formatter.parse(s, new ParsePosition(0));