Jos*_*zca 5 sql sql-server algorithm binary hex
如何使用 SQL 将数字转换为所需数字基数的字符串表示形式,例如将 45 转换为基数 2(二进制)、8(八进制)、16(十六进制)、..36。
要求使用数字[0-9]和大写字符[AZ],可用字符总数为36个。
例如,我需要将 45 转换为基数 36,输出必须为“19”,或使用任何范围基数形式 2 到 36。
这是将数字转换为任何数字基数的字符串表示形式的解决方案。解决方案是在 SQL Server 上运行的一个函数,它接收基数和数字参数。第一个参数是您要获取的基数,第二个参数是您要转换的数字。使用的算法取自网站 mathbits.com 。
如果您想将 5 以 10 为基数转换为以 2 为基数,请使用算法站点中的相同示例。
其过程是:
您可以在此处查看算法和更多示例。
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
Run Code Online (Sandbox Code Playgroud)
执行上述代码后,您可以测试它们在任何查询甚至复杂的 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]
Run Code Online (Sandbox Code Playgroud)
欢迎发表评论或提出改进建议,希望对您有用
| 归档时间: |
|
| 查看次数: |
5493 次 |
| 最近记录: |