-- 功能: 将二进制字符串(VARCHAR)转换为十进制数(INT) -- 输入参数: @StrBin 待转换的二进制字符串 -- 返回值: 相应的十进制数,如果二进制数非法,返回-1 -- 注意: @StrBin的长度不能大于31 -- 作者: cheyo@JMU Email: cheyocn at hotmail.com -- 来源: telnet://bbs.jmu.edu.cn http://bbs.jmu.edu.cn -- 日期: 2005-10-05 -- 例子: SELECT dbo.Bin2Dec('1001') AS '15的二进制表示' CREATE FUNCTION Bin2Dec(@StrBin VARCHAR(31)) RETURNS BIGINT ---- 只支持最多31位长二进制字符串的解析 AS BEGIN DECLARE @DecValue AS BIGINT -- 十进制值 DECLARE @BinLen AS TINYINT -- 二进制字符串长度 DECLARE @Index AS TINYINT -- 处理二进制字符串长度的索引 DECLARE @CurrBit AS CHAR(1) -- 当前在处理哪一位 SET @BinLen = LEN(@StrBin) SET @DecValue = 0 SET @Index = 0 WHILE @Index < @BinLen BEGIN SET @Index = @Index + 1 SET @CurrBit = CAST(SUBSTRING(@StrBin, @Index, 1) AS CHAR(1)) IF (@CurrBit <> '0' AND @CurrBit <> '1') -- 出现非法字符,返回-1 BEGIN SET @DecValue = -1 BREAK END ELSE BEGIN SET @DecValue = @DecValue * 2 IF(@CurrBit = '1') BEGIN SET @DecValue = @DecValue + POWER(2, 0) END END END RETURN @DecValue END GO