Question

I'm calculating CRC32 hash using the below code.

CRC32 crc = new CRC32();
crc.update(str.getBytes());
String enc = Long.toHexString(crc.getValue()); 

My problem is that in the output (enc) if the first character is '0' it removes that zero and finally i will get a 7 character long hex string . Can anyone tell me how can i get the full 8 character long hex string if '0' comes as the first character?

Was it helpful?

Solution

According to the Java Docs for toHexString that is expected behaviour:

This value is converted to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0s.

There are a number of ways you could go about it such as adding a leading zero character at the start of the string until the desired length is achieved, although another way would be to use the String.format method that allows the use of a C-style format specification:

String enc = String.format("%08X", crc.getValue());

Here's a complete working example for regular Java that includes computation with a leading zero:

import java.util.zip.CRC32;
import java.util.zip.Checksum;

public class HelloWorld{
     public static void main(String []args){
        String str = "c";
        CRC32 crc = new CRC32();
        crc.update(str.getBytes());
        String enc = String.format("%08X", crc.getValue());
        System.out.println(enc);
     }
}

OTHER TIPS

Hi please have a look here it was working for me, please try.

import java.util.zip.CRC32;
import java.util.zip.Checksum;

public class CalculateCRC32ChecksumForByteArray {

    public static void main(String[] args) {

        String input = "Java Code Geeks - Java Examples";

        // get bytes from string
        byte bytes[] = input.getBytes();

        Checksum checksum = new CRC32();

        // update the current checksum with the specified array of bytes
        checksum.update(bytes, 0, bytes.length);

        // get the current checksum value
        long checksumValue = checksum.getValue();

        System.out.println("CRC32 checksum for input string is: " + checksumValue);

    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top