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

Tuesday, February 10, 2015

Create executable jar on Eclipse

1. After the coding is complete, run the project as Java Application. This step is mandatory for Eclipse to create the Launch configuration info.

2. Identify the Launch configuration name by going to "Run Configurations..." (right click on project -> Run As). On the "Main" tab, there is a Name textbox on the top. The value is editable.

3. Export the project as "Runnable JAR file" (Right click on project -> Export). On the next step, select the Launch configuration for the name and set the Export destination.

4. After the jar is generated, run the application by java -jar <app_name.jar>