Monday, June 28, 2010

32-bit bitwise XOR negation value. Chinese vendor MML generate checksum in Java

Crack my head trying to make the Java equivalent of the MML checksum computation. Specification says 32-bit bitwise XOR negation value. Here's to guessing somebody might find this useful. You can just easily put this inside a method. The meat of the checksum processing is here.

int[] checksumInt = new int[4];
byte[] checksumByte = new byte[4];

StringBuffer sbuf = null;
byte[] bytesToHash = {'H','B','H','B'}; //Can be a string, just call getBytes()

//process bytesToHash in chunks of 4 bytes

for(int offset=0;offset<
bytesToHash.length;offset+=4){
checksumInt[0]^=bytesToHash[offset+0];
checksumInt[1]^=bytesToHash[offset+1];
checksumInt[2]^=bytesToHash[offset+2];
checksumInt[3]^=bytesToHash[offset+3];
}

checksumInt[0]=~checksumInt[0];
checksumInt[1]=~checksumInt[1];
checksumInt[2]=~checksumInt[2];
checksumInt[3]=~checksumInt[3];


checksumByte[0]=(byte)(checksumInt[0]&0xFF);
checksumByte[1]=(byte)(checksumInt[1]&0xFF);
checksumByte[2]=(byte)(checksumInt[2]&0xFF);
checksumByte[3]=(byte)(checksumInt[3]&0xFF);

sbuf=new StringBuffer();
for(int i=0;i<checksumByte.length;i++
sbuf.append(String.format("%X",checksumByte[i]));
}

System.out.println("The checksum: "+sbuf.toString());


An alternative way is also posted in http://forums.sun.com/thread.jspa?threadID=5354842 . Both the above and this link gave the same checksum value when given the same inputs to process.

Yet another way in .NET http://www.pcreview.co.uk/forums/thread-3652613.php

2 comments:

SrZorro said...

This is not working. if the length of bytesToHash is not divisible by 4.

The operation information is in variable length.

developer said...

I wasn't able to find my MML documentation so I just looked up my old source code. OP INFO length should be 'Nx4B'. You might want to check the MML doc though for confirmation.