SQL convert number to string representation of any base (binary, hexadecimal, …, tricontahexadecimal)

后端 未结 3 1836
感情败类
感情败类 2020-12-18 09:31

How to convert a number to it string representation for a desired numeric base using SQL, for example convert 45 to the base 2(binary), 8(octantal),16(hexadecimal), ..36.

3条回答
  •  生来不讨喜
    2020-12-18 09:45

    Hope this helps:

    -- Decimal to hex 
    SELECT CAST(493202384 AS varbinary)
    
    -- Hex to decimal 
    SELECT CAST(0x1D65ABD0 AS int)
    
    -- Decimal to hex to decimal 
    SELECT CAST(CAST(493202384 AS varbinary) AS int)
    
    -- 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
    
    -- 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
    

提交回复
热议问题