开发者

how transform c codes like that to mysql stored procs

开发者 https://www.devze.com 2023-03-10 17:37 出处:网络
C codes: unsigned int HashValue(const char *str) { const char *p = str; unsigned int hashValue = 0; while( *p != \'\\0\' )

C codes:

unsigned int HashValue(const char *str)
{
    const char *p = str;
    unsigned int hashValue = 0;
    while( *p != '\0' )
    {
        hashValue += *(unsigned char*)p;
    开发者_JAVA百科    ++p;
    }
    return hashValue;
}

My Answer:

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 ;

But:

set @str;
call HashValue(@str); 

while @str is English is ok,but change to other wide byte language(just like chinese) it works wrong;

I know the problem is the function SUBSTRING(),the second parameter is not steadily increase by one byte.

remark: mysql is utf_8 code


I have managed to solve the problem:

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 ;

Just use HEX and UNHEX.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号