Skip to content

Instantly share code, notes, and snippets.

@tijnkooijmans
Created April 17, 2014 12:53
Show Gist options
  • Save tijnkooijmans/10981093 to your computer and use it in GitHub Desktop.
Save tijnkooijmans/10981093 to your computer and use it in GitHub Desktop.
CRC-16/CCITT-FALSE
uint16_t crc16(char* pData, int length)
{
uint8_t i;
uint16_t wCrc = 0xffff;
while (length--) {
wCrc ^= *(unsigned char *)pData++ << 8;
for (i=0; i < 8; i++)
wCrc = wCrc & 0x8000 ? (wCrc << 1) ^ 0x1021 : wCrc << 1;
}
return wCrc & 0xffff;
}
@marceloiavenissi
Copy link

marceloiavenissi commented Apr 20, 2022

Javascript version:

function crc16(data, offset, length) {
    if (data == null || offset < 0 || offset > data.length - 1 || offset + length > data.length) {
        return 0;
    }

    crc = 0xFFFF;
    for (i = 0; i < length; ++i) {
        crc ^= data[offset + i] << 8;
        for (j = 0; j < 8; ++j) {
            crc = (crc & 0x8000) > 0 ? (crc << 1) ^ 0x1021 : crc << 1;
        }
    }
    return crc & 0xFFFF;
}
/**
 * data: string
 */
function crc16(data, offset, length) {
    if (data == null || offset < 0 || offset > data.length - 1 || offset + length > data.length) {
        return 0;
    }

    crc = 0xFFFF;
    for (i = 0; i < length; ++i) {
        crc ^= data.charCodeAt(offset + i) << 8;
        for (j = 0; j < 8; ++j) {
            crc = (crc & 0x8000) > 0 ? (crc << 1) ^ 0x1021 : crc << 1;
        }
    }
    return crc & 0xFFFF;
}

@IgorAlov
Copy link

IgorAlov commented Nov 3, 2022

https://github.com/IgorAlov/crc16

My variant of the function [ MySQL / MariaDB Implementation ]

DELIMITER $$

USE `database`$$

DROP FUNCTION IF EXISTS `CRC16`$$

CREATE FUNCTION `CRC16`(_STRING VARCHAR(255)) RETURNS INT(11)
    DETERMINISTIC
BEGIN
    DECLARE _CRC INT;
    DECLARE _ord INT;
    DECLARE _n INT;
    DECLARE _x INT;
    DECLARE _strlend INT;
    SET _CRC := 0xffff;

    IF (_STRING IS NULL) THEN
       RETURN NULL;
    END IF;

    SET _n  := 1;  
    SET _strlend := LENGTH(_STRING) ;
          
    loop_crc:  LOOP

       IF  _n > _strlend THEN 
         LEAVE  loop_crc;
       END  IF;

       SET _ord := ORD(SUBSTRING(_STRING, _n, 1) );
       SET _x := ((_CRC>>8) ^ _ord) & 0xff;
       SET _x := _x ^ (_x>>4);       
       SET _CRC := ((_CRC<<8) ^ (_x<<12) ^ (_x<<5) ^ _x) & 0xffff;
       SET  _n := _n + 1;
     END LOOP;
   RETURN _CRC; 

 END$$

DELIMITER ;

example query:
SELECT HEX(CRC16('bashtest'));

result:

hex(CRC16('bashtest'))  
33D0                    

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment