Conversion d'une chaîne binaire bigint dans MySQL?
Question
Je tente de hachage d'une chaîne à une valeur de 64 bits (bigint) dans MySQL. Je suis au courant de la fonction MD5 (), qui retourne un hachage de 128 bits comme une chaîne binaire. Je serais heureux de prendre juste le bas ou en haut de 64 bits de ce résultat. Cependant, je ne peux pas comprendre comment obtenir à partir d'un type de chaîne binaire à un type numérique de toute sorte. Tous les pointeurs?
La solution
Utilisez la fonction CONV()
pour convertir le hachage MD5 de base 16 à la base 10 et CAST
pour le convertir en un nombre:
select cast(conv(substring(md5(id), 1, 16), 16, 10) as unsigned integer) from SomeTable;
Autres conseils
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
Vous pourriez aussi utiliser la fonction CRC32
qui renvoie la valeur 32 bits non signé.
SELECT CRC32(id) from SomeTable;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow