Added some masking to prevent a byte with the high bit set (0x80 or more) to flip into negative numbers; also altered to use an int in update.

This commit is contained in:
Robert Greene 2008-06-17 04:09:03 +00:00
parent 27ee990c43
commit 6c241ea036
2 changed files with 8 additions and 3 deletions

View File

@ -40,7 +40,7 @@ public class CRC16 implements Checksum {
*/ */
private int update(int crc, byte[] bytes, int off, int len) { private int update(int crc, byte[] bytes, int off, int len) {
for (int i = off; i < (off + len); i++) { for (int i = off; i < (off + len); i++) {
byte b = bytes[i]; int b = (bytes[i] & 0xff);
crc = (table[((crc >> 8) & 0xff) ^ b] ^ (crc << 8)) & 0xffff; crc = (table[((crc >> 8) & 0xff) ^ b] ^ (crc << 8)) & 0xffff;
} }
return crc; return crc;
@ -64,7 +64,7 @@ public class CRC16 implements Checksum {
* @param b input byte * @param b input byte
*/ */
public void update(int b) { public void update(int b) {
byte[] ba = { (byte) b }; byte[] ba = { (byte) (b & 0xff) };
value = update(value, ba, 0, 1); value = update(value, ba, 0, 1);
} }

View File

@ -5,7 +5,6 @@ import java.io.UnsupportedEncodingException;
import junit.framework.TestCase; import junit.framework.TestCase;
public class CRC16Test extends TestCase { public class CRC16Test extends TestCase {
public void testTable() { public void testTable() {
int[] table = CRC16.getTable(); int[] table = CRC16.getTable();
assertEquals(0, table[0]); assertEquals(0, table[0]);
@ -30,4 +29,10 @@ public class CRC16Test extends TestCase {
assertEquals(0x31c3, crc16.getValue()); assertEquals(0x31c3, crc16.getValue());
} }
public void testVariousValues() throws UnsupportedEncodingException {
CRC16 crc16 = new CRC16();
byte[] data = new byte[] { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, (byte)0x80 };
crc16.update(data);
assertEquals(0x2299, crc16.getValue());
}
} }