Wrong CRC32 hash in android

akh

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?

PeterJ

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);
     }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related