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

发布于 2024-08-01 23:51:57 字数 148 浏览 4 评论 0原文

我正在尝试将 MySQL 中的字符串哈希为 64 位值(bigint)。 我知道 MD5() 函数,它以二进制字符串形式返回 128 位哈希值。 我很乐意只取这个结果的底部或顶部 64 位。 但是,我无法弄清楚如何从二进制字符串类型转换为任何类型的数字类型。 有什么指点吗?

I am attempting to hash a string to a 64-bit value (bigint) in MySQL. I am aware of the MD5() function, which returns a 128-bit hash as a binary string. I'd be happy to just take the bottom or top 64 bits of this result. However, I cannot figure out how to get from a binary string type to a numeric type of any sort. Any pointers?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

各自安好 2024-08-08 23:51:57

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

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

Use the CONV() function to convert the MD5 hash from base 16 to base 10 and CAST to convert it to a number:

select cast(conv(substring(md5(id), 1, 16), 16, 10) as unsigned integer) from SomeTable;
酷到爆炸 2024-08-08 23:51:57
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 

来源< /a>

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

一杆小烟枪 2024-08-08 23:51:57

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

SELECT CRC32(id) from SomeTable;

文档

You could also use CRC32 function that returns 32-bit unsigned value.

SELECT CRC32(id) from SomeTable;

Documentation

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文