Click to See Complete Forum and Search --> : Check a CRC16. Problem with int and short types


AlbertGM
July 6th, 2009, 08:03 AM
Hi all,
Let a byte array I wanna check the crc out, but I have a problem. I use CRC-16, so I need a short type. CRC code is in the last two bytes of array, so I try to do:

public Message (byte[] data){ // last two bytes contains crc
super(data);
int posCRC = data.length - 2;
short crc = (data[posCRC] << 8) | data[posCRC+1]; (*)

// here I work out the CRC and check they are the same
}
In (*) compiler tells me: "cannot convert int to short". Why? It is 2 bytes length, and it should be stored in a short type variable, shouldn't it?
I tried to cast, but it doesn't let me.
I cannot use int type because my CRC function returns a short (2 bytes), which can be negative if is bigger than 0x8000. However if I use int type 0x8000 (or any other 4 bytes length value) is always positive.
This could be solved using unsigned but Java hasn't.

So, I'd like to check if given crc (two bytes) is agree to the calculated (short type). Any hint?

Thanks a lot

Albert.

dlorde
July 6th, 2009, 08:18 AM
I tried to cast, but it doesn't let me.
Works fine for me:short crc = (short) ((data[posCRC] << 8) | data[posCRC + 1]);Eighty percent of success is showing up...
W. Allen

AlbertGM
July 6th, 2009, 08:28 AM
Upsss!! I swear I tried to cast and it didn't work before... well, I guess :blush:

Thanks a lot, it works perfectly.

Albert.