MySQL将hex转换为double

时间:2014-09-14 17:43:26

标签: mysql

在MySQL中应该采用哪种方式将HEX(8字节)转换为double值?

要从HEX转换为INT,我使用CONV(hex_value,16,10)。但是为了将转换为双倍,我不知道。

CREATE FUNCTION HEX2DOUBLE(hex_input TEXT) RETURNS DOUBLE
DETERMINISTIC
BEGIN
DECLARE hex_bits VARCHAR(64);

DECLARE sign_bit VARCHAR(1);
DECLARE expoent_bits VARCHAR(11);
DECLARE mantissa_bits VARCHAR(52);

DECLARE i INT;
DECLARE mantissa DOUBLE;
DECLARE expoent INT;
DECLARE result DOUBLE;

SET hex_bits = LPAD(CONV(hex_input, 16, 2), 64, '0');

SET sign_bit = SUBSTR(hex_bits, 1, 1);
SET expoent_bits = SUBSTR(hex_bits, 2, 11);
SET mantissa_bits = SUBSTR(hex_bits, 13, 52);

SET expoent = CONV(expoent_bits, 2, 10)-1023;

SET i = 1;

SET mantissa = 0;
WHILE(i <= 52) DO
    IF SUBSTR(mantissa_bits, i , 1 ) = '1' THEN 
        SET mantissa  =  mantissa +  1/POWER(2, i);        
    END IF;
    SET i = i + 1;
END WHILE;

IF(expoent > -1023) THEN
    SET mantissa = mantissa + 1;
END IF;

SET result = POWER(2, expoent) * mantissa;
IF(sign_bit = 1) THEN
    SET result = -1 * result;
END IF;

RETURN result;
END//

以上似乎大部分时间都有用。你们可以说些什么呢?我面临的一个问题是 SQL错误(1690):在pow(2,expoent @ 7)中DOUBLE值超出范围,我认为这是对SET result = POWER(2, expoent) * mantissa;

的引用

0 个答案:

没有答案