crc16-xmodem.ts

Simple implementation of crc16-xmodem
git clone git://git.finwo.net/lib/crc16-xmodem.ts
Log | Files | Refs | README | LICENSE

0000-crc16.ts (1590B)


      1 import { crc16, crc16b } from '../src';
      2 import test from 'tape';
      3 
      4 const knownValues: [string,number][] = [
      5   ["Hello World\0\0"  , 0x992A],
      6   ["Hello World!\0\0" , 0x0CD3],
      7   ["Pizza Calzone\0\0", 0x795B],
      8 ];
      9 
     10 test('Testing CRC-16/XMODEM', t => {
     11   const message = Buffer.from('Hi!\0\0');
     12 
     13   // The buffer-variant re-uses this method
     14   const val_0 = crc16(message);
     15   t.equal(val_0, 12797 , "'Hi!' produces good known-value numerically");
     16 
     17   // Validate the number is converted to a buffer correctly
     18   const val_1 = crc16b(message);
     19   t.equal(val_1.toString('hex'), "31fd", "'Hi!' produces good known-value as buffer");
     20 
     21   console.log(val_1);
     22 
     23   // Validate all known values in the table
     24   for(const check of knownValues) {
     25     t.equal(crc16(Buffer.from(check[0], 'ascii')), check[1], `known value '${check[0].slice(0,check[0].length-2)}' produces correct output`);
     26   }
     27 
     28   // Check inverse
     29   for(const check of knownValues) {
     30     const nb = Buffer.from(check[0], 'ascii');
     31     nb.writeUInt16BE(crc16(nb), nb.length - 2);
     32     t.equal(crc16(nb), 0, `inverse '${check[0].slice(0,check[0].length-2)}' resolves to 0 when no errors introduced`);
     33     nb[0]++;
     34     t.notEqual(crc16(nb), 0, `inverse '${check[0].slice(0,check[0].length-2)}' resolves to non-0 with increment error`);
     35     nb[0]--;
     36     nb[1] ^= 0x02;
     37     t.notEqual(crc16(nb), 0, `inverse '${check[0].slice(0,check[0].length-2)}' resolves to non-0 with 1 bit-flip`);
     38     nb[1] ^= 0x04;
     39     t.notEqual(crc16(nb), 0, `inverse '${check[0].slice(0,check[0].length-2)}' resolves to non-0 with 2 consecutive bit-flips`);
     40   }
     41 
     42   t.end();
     43 });