How to calculate the CRC32 of a string in Java

1 Answer

0 votes
import java.util.zip.CRC32;
import java.nio.charset.StandardCharsets;

public class Main {

    /**
     * Calculates the CRC32 checksum of a string.
     *
     * @param input The string to hash.
     * @return The CRC32 value formatted as an 8‑character uppercase hex string.
     */
    public static String crc32OfString(String input) {
        // CRC32 is a built‑in Java class that implements the standard CRC‑32 algorithm
        CRC32 crc = new CRC32();

        // Convert the string to bytes using UTF‑8 encoding
        byte[] bytes = input.getBytes(StandardCharsets.UTF_8);

        // Feed the bytes into the CRC32 calculator
        crc.update(bytes);

        // Get the computed CRC32 value (stored in a long)
        long value = crc.getValue();

        // Format as 8‑digit uppercase hexadecimal (common CRC32 representation)
        return String.format("%08X", value);
    }

    public static void main(String[] args) {
        String text = "Java Programming";

        // Compute the CRC32 of the string
        String crc = crc32OfString(text);

        System.out.println("CRC32: " + crc);
    }
}



/*
run:

CRC32: B8A315AC

*/

 



answered May 8 by avibootz
...