在MySQL中将二进制字符串转换为bigint?

问题描述 投票:8回答:3

我试图在MySQL中将字符串哈希到64位值(bigint)。我知道MD5()函数,它返回一个128位散列作为二进制字符串。我很乐意把这个结果的底部或前64位。但是,我无法弄清楚如何从二进制字符串类型到任何类型的数字类型。有什么指针吗?

mysql hash binary md5 bigint
3个回答
14
投票

使用CONV()函数将MD5哈希值从基数16转换为基数10,使用CAST将其转换为数字:

select cast(conv(substring(md5(id), 1, 16), 16, 10) as unsigned integer) from SomeTable;

2
投票
CREATE FUNCTION dbo.HexStrToVarBinary(@hexstr varchar(8000))
RETURNS varbinary(8000)
AS
BEGIN 
    DECLARE @hex char(1), @i int, @place bigint, @a bigint
    SET @i = LEN(@hexstr) 

    set @place = convert(bigint,1)
    SET @a = convert(bigint, 0)

    WHILE (@i > 0 AND (substring(@hexstr, @i, 1) like '[0-9A-Fa-f]')) 
     BEGIN 
        SET @hex = SUBSTRING(@hexstr, @i, 1) 
        SET @a = @a + 
    convert(bigint, CASE WHEN @hex LIKE '[0-9]' 
         THEN CAST(@hex as int) 
         ELSE CAST(ASCII(UPPER(@hex))-55 as int) end * @place)
    set @place = @place * convert(bigint,16)
        SET @i = @i - 1

     END 

    RETURN convert(varbinary(8000),@a)
END
GO 

Source


0
投票

您还可以使用返回32位无符号值的CRC32函数。

SELECT CRC32(id) from SomeTable;

Documentation

© www.soinside.com 2019 - 2024. All rights reserved.