4

i'm trying to implement a CRC-CCITT (XModem) check in javascript without success. I need it in order to send socket string into a controller via RS232. does anyone know how to do it? or perhaps is there a sample code somewhere??

I would appreciate any kind of help :)

Salmonela
  • 41
  • 1
  • 2

2 Answers2

1

A quick search showed http://zorc.breitbandkatze.de/crc.html which is an online CRC calculator in Javascript. It looks like it's quite general purpose because all CRC parameters can be changed, so it may be much more than what you're looking for. However, the same techniques will apply for your application.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • hi Greg, thanks for your answer, however the online calculator you proposed does not calculate the XModem correctly - "question#2: in c-code, be careful using polynoms having a LSB of 0 (e. g. XMODEM 0x8408)... code doesn't work for such cases!!! Any ideas how to convert direct to nondirect values with polynoms having LSB=0?" so i still do not have a sample code that does it. – Salmonela Jun 30 '10 at 16:39
  • @Salmonela: I've used that online CRC calculator before and it is correct. You must be careful with things like bit order and reciprocal polynomial values. The best option might be to find some simple C code that does what you want, and convert that to Javascript. The completed function should be about 10 lines of code. – Greg Hewgill Jul 01 '10 at 00:38
0

Due to its rather unique polynomial, the CRC-16 variant XMODEM uses can be implemented efficiently in JavaScript with optimal performance.

This function will produce the XMODEM CRC-16 of a given string:

function crc16(str, crc = 0, xorout = 0) {
    for(let i = 0, t; i < str.length; i++, crc &= 0xFFFF) {
        t = (crc >> 8) ^ str.charCodeAt(i);
        t ^= t >> 4;
        crc = (crc << 8) ^ (t << 12) ^ (t << 5) ^ t;
    }
    return crc ^ xorout;
}

// Check if test string matches expected result
console.log(crc16("123456789") === 0x31c3);

It's worth noting that this function can also be used to specify certain other variants of CRC-16. For example, initializing crc to 0xFFFF will correctly model the CRC-16 variant used on IBM 3740 floppy disks.

The XMODEM CRC-16 is sometimes misidentified as the more common CCITT CRC-16 (less-confusingly known as the KERMIT CRC-16). They are nearly identical. The only difference is that XMODEM uses an unreflected polynomial, whereas KERMIT uses a reflected polynomial.

So purely for comparison purposes, here is the KERMIT CRC-16 version:

function crc16_refl(str, crc = 0, xorout = 0) {
    for(let i = 0, t; i < str.length; i++, crc &= 0xFFFF) {
        t = crc ^ str.charCodeAt(i);
        t ^= t << 4, t &= 0xFF;
        crc = (crc >> 8) ^ (t << 8) ^ (t >> 4) ^ (t << 3);
    }
    return crc ^ xorout;
}

// Check if test string matches expected result
console.log(crc16_refl("123456789") === 0x2189);
bryc
  • 12,710
  • 6
  • 41
  • 61