如何在SQL Server中将二进制转换为整数

我有35个字符的二进制代码,并具有预期的输出。需要有关如何在SQL Server中进行转换的逻辑。

输入(二进制):00000110010110110001110101101110100
预期输出(int):816570

谢谢。

kakalb 回答:如何在SQL Server中将二进制转换为整数

尝试使用递归CTE进行以下查询:

declare @bit varchar(50) = '00000110010110110001110101101110100'

;with cte as (
    select 0 [bit],cast(1 as bigint) powerOf2,substring(@bit,len(@bit) - 1,1) [bitValue]
    union all
    select [bit] + 1,powerOf2 * 2,len(@bit) - [bit] - 1,1)
    from cte
    where [bit] + 1 < len(@bit)
)

select sum(powerOf2 * bitValue) from cte

将第二列设为bigint很重要,这样它可以容纳大整数值:)

本文链接:https://www.f2er.com/3066546.html

大家都在问