Skip to content

Instantly share code, notes, and snippets.

@tijnkooijmans
Created April 17, 2014 12:53
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • 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;
}
@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