Skip to content

Instantly share code, notes, and snippets.

@SunboX
Created December 15, 2022 08:47
Show Gist options
  • Save SunboX/fa5e4152e0fbe44fa0587583dc520cf1 to your computer and use it in GitHub Desktop.
Save SunboX/fa5e4152e0fbe44fa0587583dc520cf1 to your computer and use it in GitHub Desktop.
Qt qChecksum implementation in Node.js / JavaScript

I thought this might be helpful for someone some time:

const crc_tbl = [
    0x0000, 0x1081, 0x2102, 0x3183,
    0x4204, 0x5285, 0x6306, 0x7387,
    0x8408, 0x9489, 0xa50a, 0xb58b,
    0xc60c, 0xd68d, 0xe70e, 0xf78f
]

/*! 
    \relates QByteArray
    Returns the CRC-16 checksum of the first \a len bytes of \a data.
    The checksum is independent of the byte order (endianness).
    \note This function is a 16-bit cache conserving (16 entry table)
    implementation of the CRC-16-CCITT algorithm.
*/

function qChecksum(data, len)
{
    let crc = 0xffff
    let c
    let p = 0
    while (len--) {
        c = data[p++]
        crc = ((crc >> 4) & 0x0fff) ^ crc_tbl[((crc ^ c) & 15)]
        c >>= 4
        crc = ((crc >> 4) & 0x0fff) ^ crc_tbl[((crc ^ c) & 15)]
    }
    return ~crc & 0xffff
}

usage:

const hex = 'xxxxxx'
let buf = Buffer.from(hex, 'hex')

console.log(qChecksum(buf, buf.length))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment