Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsigned Bytes CRC32 in Java

I'm trying to replicate the CRC32 hashing function that is available in PHP in Java. The existing CRC32 class within Java returns a different hash and I believe it is because the Java bytes in my byte array are unsigned -128 through 128 instead of 0-255.

What I'm failing to figured out is how to work around this situation. I've looked at using Guava's UnsignedBytes, but I can't find a hashing method that takes it as an argument. I could use that to write my own hashing function, but frankly I don't nearly enough about how it works or bitwise arithmetic in general to make that plausible.

In the simplest terms I'm trying to CRC32 has a string and return the decimal representation.

like image 701
Nick Avatar asked May 27 '26 23:05

Nick


1 Answers

CRC does not care about sign.

Java's CRC32 gave me same result than PHP's.

public static void main(String[] args) {
    String a = "Hello World!";
    CRC32 crc = new CRC32();
    crc.update(a.getBytes());
    System.out.println(Long.toHexString(crc.getValue()));
}

Outputs: 1c291ca3

Using this online PHP CRC32 calculator gave the same CRC value than above Java code.

like image 131
m0skit0 Avatar answered May 30 '26 12:05

m0skit0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!