C代码:
unsigned int HashValue(const char *str)
{
const char *p = str;
unsigned int hashValue = 0;
while( *p != '\0' )
{
hashValue += *(unsigned char*)p;
++p;
}
return hashValue;
}
我的回答:
DELIMITER $$
CREATE
PROCEDURE `test`.`HashValue`(IN str CHAR(32))
BEGIN
SET @size = LENGTH(str);
SET @pos = 1;
SET @hashValue = 0;
WHILE @pos<@size+1 DO
SET @nCh = SUBSTRING(str,@pos,1);
SET @hashValue = @hashValue + ASCII(@nCh);
SET @pos = @pos + 1;
END WHILE;
SELECT @hashValue;
END$$
DELIMITER ;
可是:
set @str;
call HashValue(@str);
虽然@str
是英语,但是改为其他宽字节语言(就像中文一样)它的工作错误;
我知道问题是函数SUBSTRING()
,第二个参数不会稳定地增加一个字节。
备注: mysql是utf_8代码
答案 0 :(得分:0)
我设法解决了这个问题:
DELIMITER $$
CREATE
PROCEDURE `test`.`HashValue`(IN str CHAR(32))
BEGIN
SET @pos = 1;
SET @hashValue = 0;
SET @szHex = HEX(str);
SET @size = LENGTH(@szHex);
WHILE @pos<@size+1 DO
SET @cCh = SUBSTRING(@szHex,@pos,2);
SET @nCh =CAST(ASCII(UNHEX(@cCh)) AS UNSIGNED);
SET @hashValue = @hashValue + @nCh;
SET @pos = @pos + 2;
END WHILE;
SELECT @hashValue;
END$$
DELIMITER ;
只需使用HEX
和UNHEX
。