user1534664 user1534664 - 2 years ago 60
Java Question

How does this piece of code verify a checksum?

My teacher ported the Darwin-OP Framework from C++ to Java, allowing students like me to use it without having to master C++. Darwin has two controllers: the main controller runs Linux and runs the java code, and has a serial connection with the sub controller (a microcontroller) that controls all the sensors/servo's/transducers etc.

Darwin uses a motion.bin file in which it stores a list of 256 pages. Each page is 512 (8 * 64) bytes, and consists of 7 steps (64 bytes each) plus a page header (also 64 bytes). Each steps contains positions (a value between 0-4095) for the servo to take. So for Darwin to move his arm, he goes through (<7) amount of steps until he finishes the final step.

Inside the page header there is a checksum of 1 byte. The Java code contains two methods in which the checksum is calculated and verified:

private static boolean VerifyChecksum(PAGE page) {
byte checksum = (byte)0x00;
byte[] pagebytes = page.GetBytes();
for (int i = 0; i < pagebytes.length; i++) {
checksum += pagebytes[i];
if (checksum != (byte)0xFF) {
return false;
return true;

private static void SetChecksum(PAGE page) {
byte checksum = (byte)0x00;
byte[] pagebytes = page.GetBytes();
page.header.checksum = (byte)0x00;
for (int i = 0; i < pagebytes.length; i++) {
checksum += pagebytes[i];
page.header.checksum = (byte)((byte)0xFF - checksum);

Main question: Can someone explain how the checksum is verified? I don't understand why it checks
checksum != (byte)0xFF
. Why not just compare the calculated

Bonus question: Why check the file integrity in the first place? Would it be that common for a page inside a .bin file to become corrupted?

Answer Source

To compute the checksum, you perform an XOR of all the bytes in the file, then return 0xFF minus that value.
The file passed in to the checksum method is the final file with 0x00 in the checksum position.

sum = 0xFF - XOR(file)

For binary, addition is the same as XOR, hence the line checksum += pagebytes[i];

Your professor's verification method, will XOR the entire file. Which is to say, the original argument to the checksum method, and an additional byte which is the output of the checksum method.

So the expected result is then:

XOR(file, sum)
= XOR(file) + sum
= XOR(file) + 0xFF - XOR(file)
= 0xFF
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download