0

I am working on something and I am required to calculate checksum with every data sent. This checksum is the Lower 2 bytes of the 4 byte sum of all the bytes

Assume I have the data as:

Bytebuffer buffer = Bytebuffer.allocate(128); // assume i have filled buffer with some data

Below is how I am find the sum of all bytes and then getting the lower of 2 bytes.

byte array = buffer.array();
int checksum = 0;

for(byte b : array){
  checksum += (int)b
}

checksum = (checksum & 0xff00ff) + ((checksum >> 0x08) & 0xff00ff);
short result = (short) (checksum + (checksum >> 0x10));

However, the application listening for this data tells me the checksum is wrong. What could be wrong in my logic of thinking? Thanks in Advance

Kaleb Blue
  • 487
  • 1
  • 5
  • 20

1 Answers1

0

Don't read from the buffer's backing array(). You should not normally access that array directly. It ignores the buffer's limit, and position. Instead, use the get() methods. A bulk get:

byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);

or individual gets:

while (buffer.hasRemaining()) {
    checksum += buffer.get() & 0xff;
}

Note that if you've filled the buffer up with put() calls, you need to call flip().

After a sequence of channel-read or put operations, invoke this method to prepare for a sequence of channel-write or relative get operations.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Thanks, it seems like the original buffer is being modified though. Is there a way not to that? – Kaleb Blue Jun 16 '17 at 14:09
  • That's how `ByteBuffer`s work. They're like files with positioning markers that update as you read and write. It's not something you should try to avoid. – John Kugelman Jun 16 '17 at 15:33