Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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;  
            else
                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:

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?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe