crc16-xmodem.ts

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

index.ts (979B)


      1 // See https://crccalc.com/?crc=Hi!&method=CRC-16/XMODEM&datatype=ascii&outtype=hex
      2 
      3 // Main configuration
      4 // Note: we do not support RefIn or RefOut
      5 const polynomial = 0x1021;
      6 const init       = 0x0000;
      7 const xorout     = 0x0000;
      8 
      9 // Pre-calculate reference table
     10 // Allows us to process byte-for-byte instead of bit-for-bit
     11 const crcTable = [];
     12 for(let i=0 ; i < 256 ; i++) {
     13   let virt = (i << 16);
     14   for(let s = 7 ; s >= 0 ; s--)
     15     if (virt & (0x10000 << s)) virt ^= (0x10000|polynomial) << s;
     16   crcTable[i] = virt + (i << 16); // Re-mix in i, to clear higher bits during calculation
     17 }
     18 
     19 export function crc16(subject: Buffer | Uint8Array): number {
     20   let result = init;
     21   for(let i = 0 ; i < subject.length ; i++) {
     22     result  = ((result << 8) + subject[i]) ^ crcTable[result >> 8];
     23   }
     24   return result ^ xorout;
     25 }
     26 
     27 export function crc16b(subject: Buffer | Uint8Array): Buffer {
     28   const result = Buffer.alloc(2);
     29   result.writeUInt16BE(crc16(subject));
     30   return result;
     31 }