Friday, February 27, 2015

CRC32 calculation on Java and Objective-C

CRC32.md

One time I had to calculate CRC32 checksum for image files on Java and Objective-C. But I could not get the results matched when I tried to read the file via UIImagePickerController on Objective-C. I knew the result from Java was correct because this website returned the same checksum. The myth was finally resolved when I loaded the file from resource by using NSBundle.

Source code

code snippet in Java

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.CRC32;

...
try {
    Path path = Paths.get("path/to/image.jpg");
    byte[] data = Files.readAllBytes(path);
    Checksum checksum = new CRC32();
    checksum.update(data, 0, data.length);
    long result = checksum.getValue();
    System.out.println("file crc32 cheksum: " + result);
} catch (IOException e){
    e.printStackTrace();
}

code snippet in Objective-C

you will need to add libz.dylib in Linked Frameworks and Libraries in General tab on Xcode.

#include <zlib.h>;

...
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
uLong crc = crc32(0L, Z_NULL, 0);
long long result = crc32(crc, [data bytes], [data length]);
NSLog(@"file crc32 checksum %llu", result));

No comments:

Post a Comment