SQL 将数字转换为任何基数的字符串表示形式(二进制、十六进制、...、三十六进制)

标签 sql sql-server algorithm binary hex

如何使用 SQL 将数字转换为所需数字基数的字符串表示形式,例如将 45 转换为基数 2(二进制)、8(八进制)、16(十六进制)、..36。

要求是使用数字[0-9]和大写字符[A-Z],总共可用字符为36个。

我需要将例如 45 转换为基数 36,输出必须为“19”,或者使用 2 到 36 之间的任何范围基数。

最佳答案

这是将数字转换为字符串表示形式到任何数字基数的解决方案。该解决方案是一个在 SQL Server 上运行的函数,它接收基数和数字参数。第一个参数是你想要得到的基数,第二个参数是你想要转换的数字。 The algorithm used取自网站 mathbits.com。

使用来自 site of the algorithm 的相同示例, 如果你想将 5 以 10 为底数转换为以 2 为底数。

enter image description here

过程是:

  1. 将“所需”基数(在本例中为基数 2)除以您要转换的数字。
  2. 像在小学时那样写出商(答案)和余数。
  3. 使用前一个商的整数(余数前面的数字)重复这个除法过程。
  4. 继续重复这个除法,直到余数前面的数只为零。
  5. 答案是从下往上读的余数。

你可以看到 algorithm and more examples here .

SQL 中的函数是使它们在 SQL Server 实例中全局可用的最佳选择,进行转换的代码如下:

IF OBJECT_ID (N'dbo.NUMBER_TO_STR_BASE', N'FN') IS NOT NULL
    DROP FUNCTION dbo.NUMBER_TO_STR_BASE;
GO
CREATE FUNCTION dbo.NUMBER_TO_STR_BASE (@base int,@number int)
RETURNS varchar(MAX)
WITH EXECUTE AS CALLER
AS
BEGIN
     DECLARE @dividend int = @number
        ,@remainder int = 0 
        ,@numberString varchar(MAX) = CASE WHEN @number = 0 THEN '0' ELSE '' END ;
     SET @base = CASE WHEN @base <= 36 THEN @base ELSE 36 END;--The max base is 36, includes the range of [0-9A-Z]
     WHILE (@dividend > 0 OR @remainder > 0)
         BEGIN
            SET @remainder = @dividend % @base ; --The reminder by the division number in base
            SET @dividend = @dividend / @base ; -- The integer part of the division, becomes the new divident for the next loop
            IF(@dividend > 0 OR @remainder > 0)--check that not correspond the last loop when quotient and reminder is 0
                SET @numberString =  CHAR( (CASE WHEN @remainder <= 9 THEN ASCII('0') ELSE ASCII('A')-10 END) + @remainder ) + @numberString;
     END;
     RETURN(@numberString);
END
GO

执行上述代码后,您可以测试它们在任何查询中甚至在复杂的 TSL 代码中调用函数。

SELECT dbo.NUMBER_TO_STR_BASE(16,45) AS 'hexadecimal';
-- 45 in base 16(hexadecimal) is 2D 
SELECT dbo.NUMBER_TO_STR_BASE(2,45) AS 'binary';
-- 45 in base 2(binary) is 101101
SELECT dbo.NUMBER_TO_STR_BASE(36,45) AS 'tricontahexadecimal';
-- 45 in base (tricontaexadecimal) is 19
SELECT dbo.NUMBER_TO_STR_BASE(37,45) AS 'tricontahexadecimal-test-max-base';
--The output will be 19, because the maximum base is 36,
-- which correspond to the characters [0-9A-Z]

随时评论或提出改进建议,希望对您有用

关于SQL 将数字转换为任何基数的字符串表示形式(二进制、十六进制、...、三十六进制),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33092823/

相关文章:

java - jdbc 连接到 SQL Server

c# - 处理一个单词,使用字符串或字符数组或字符串构建器陷入困境?

sql - 为什么分解这个相关子查询 vaSTLy 可以提高性能?

php - 合并具有不同外键多个值的同一产品 ID 的多个实例?

sql - 在 View 中使用带有 SQL 函数的联接

python - 为半径 r 内的所有点查询 "Annoy"索引

c++ - 给定一个区间 vector ,输出区间内重叠次数最多的任意一个数

java - JPA 查询结果为 No Identifier

sql - 搜索 holiday doy IN(字符串)(Postgresql)

sql - 添加非聚集索引会锁定我的表吗?