Bret Hodgson
Bret Hodgson

Reputation: 113

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

Upvotes: 1

Views: 2883

Answers (2)

Andreas
Andreas

Reputation: 159086

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

Upvotes: 3

HopefullyHelpful
HopefullyHelpful

Reputation: 1799

The following code should do it for you.

public static int checkSum(byte[] input) {
   int checkSum = 0;
   for(byte b : input) {
      checkSum += b & 0xFF;
   }
   return checkSum;
}

The b & 0xFF converts the byte to an integer and gives it it's unsigned value, that means 255 will be interpreted as 255 instead of -1.

Upvotes: 1

Related Questions