Convert decimal <--> binary with T-SQL

梦想的初衷 提交于 2021-02-20 03:51:16

问题


How can I convert binary (base 2 stored as varchar) into decimal (base 10 stored as int or bigint) and the other way around, using T-SQL?

Example results:

  • 7 (dec) <--> 111 (bin)
  • 136 (dec) <--> 10001000 (bin)
  • 2123942362 (dec) <--> 1111110100110001100100111011010 (bin)

回答1:


This answer can handle bigint

Convert to bit(varchar containing 1 and 0)

DECLARE @input BIGINT = 9223372036854775807

;WITH N(N)AS 
(
  SELECT top 63
    POWER(cast(2 as bigint),
      ROW_NUMBER()over(ORDER BY (SELECT 1))-1)
  FROM
    (VALUES(1),(1),(1),(1))M(a),
    (VALUES(1),(1),(1),(1))L(a),
    (VALUES(1),(1),(1),(1))K(a)
)
SELECT
  COALESCE
  (
    REVERSE
    (
      ( 
        SELECT CAST(@input/N%2 as CHAR(1))
        FROM N 
        WHERE N <= @input
        for xml path(''), type 
      ).value('.', 'varchar(max)')
    )
    , '0'
  )

Result:

111111111111111111111111111111111111111111111111111111111111111

Convert varchar containing bit values to bigint

DECLARE @input varchar(max) = 
  '111111111111111111111111111111111111111111111111111111111111111'

;WITH N(V) AS 
(
  SELECT
    ROW_NUMBER()over(ORDER BY (SELECT 1))
  FROM
    (VALUES(1),(1),(1),(1))M(a),
    (VALUES(1),(1),(1),(1))L(a),
    (VALUES(1),(1),(1),(1))K(a)
)
SELECT SUM(SUBSTRING(REVERSE(@input),V,1)*POWER(CAST(2 as BIGINT), V-1))
FROM   N
WHERE  V <= LEN(@input)

Result:

9223372036854775807



回答2:


You could get integers from master.dbo.spt_values and use them as the weight for each digit.

use master;

declare @binary     as  varchar(max)    =   '1111110100110001100100111011010';
declare @decimal    as  int             =   2123942362;

--binary --> decimal
select  
    @binary                                                     as  binaryValue
,   sum(    substring(@binary,len(@binary)-position.number,1) 
        *   power(2,position.number) )                          as  decimalValue
FROM    dbo.spt_values  AS  position
WHERE   position."type" =   'P'     --integers
    and position.number <=  len(@binary)-1
;

--decimal --> binary
select  
    @decimal                                                    as  decimalValue
,   (
        SELECT  CAST(sign(@decimal & power(2,position.number)) as varchar(max))
        FROM    dbo.spt_values  AS  position
        WHERE   position."type" =   'P'     --integers
            and position.number <=  isnull(LOG(nullif(@decimal,0),2),0)
        order by    position.number desc
        FOR XML PATH(''),TYPE
    ).value('(./text())[1]','VARCHAR(8000)')                    as  binaryValue



回答3:


You can create two functions as below and then create a wrapper function that would have a bit input to say which format are you trying to convert.

Converting binary to decimal

CREATE FUNCTION [dbo].[BinaryToDecimal]
(
    @Input varchar(255)
)
RETURNS bigint
AS
BEGIN

    DECLARE @Cnt tinyint = 1
    DECLARE @Len tinyint = LEN(@Input)
    DECLARE @Output bigint = CAST(SUBSTRING(@Input, @Len, 1) AS bigint)

    WHILE(@Cnt < @Len) BEGIN
        SET @Output = @Output + POWER(CAST(SUBSTRING(@Input, @Len - @Cnt, 1) * 2 AS bigint), @Cnt)

        SET @Cnt = @Cnt + 1
    END

    RETURN @Output  

END

Converting decimal to binary

CREATE FUNCTION [dbo].[DecimalToBinary]
(
    @Input bigint
)
RETURNS varchar(255)
AS
BEGIN

    DECLARE @Output varchar(255) = ''

    WHILE @Input > 0 BEGIN

        SET @Output = @Output + CAST((@Input % 2) AS varchar)
        SET @Input = @Input / 2

    END

    RETURN REVERSE(@Output)

END

Hope this helps



来源:https://stackoverflow.com/questions/43736580/convert-decimal-binary-with-t-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!