Search code examples
javaasciichecksum

Computing Checksum of byte[] in Java with expected result


I need some help with a problem that I just cannot solve. What I have to do is calculate the Checksum of a known byte[]. Lets start with the known values:

I must convert an 8 digit value to 8 bytes of ASCII:

Value = 33053083
Converted (asciiValue) = 33:33:30:35:33:30:38:33

This is correct, as it matches the expected value given to me.

Next, I need to "Compute the checksum of the ASCII value (asciiValue). Extract the last 2 digits (right justified). The result is the 'Checksum'."

I know the value of this computed checksum is supposed to be 99.

I've looked everywhere and tried just about everything, but I cannot come up with the expected value of 99.

Thank you for the help!

Edited to add given algorithm (in C):

unsigned char
vls_byteSum(char *blk, int len)
{
   int i;
   unsigned char sum = 0;
   for (i=0; i < len; ++i)
      sum += blk[i];
      return sum;
}

Solution

  • The code you posted in a comment is pretty much correct, except change char to byte:

    public static byte vls_byteSum(byte[] blk) {
        byte sum = 0;
        for (int i = 0; i < blk.length; i++)
            sum += blk[i];
        return sum;
    }
    

    Test it with this:

    byte result = vls_byteSum(new byte[] { 0x33, 0x33, 0x30, 0x35, 0x33, 0x30, 0x38, 0x33 });
    System.out.printf("0x%02x = %d = %d", result, result, Byte.toUnsignedInt(result));
    

    Output:

    0x99 = -103 = 153