2013年3月20日

TSQL/C# 撰寫10進制轉任何進制

以下展示C#和TSQL怎麼寫10進制,轉換成任何的進制,基本原理請參考這裡

CREATE FUNCTION dbo.f_convert_from_base10
(@num INT, @base TINYINT)
RETURNS VARCHAR(255) AS
BEGIN

-- Declarations
DECLARE @string VARCHAR(255)
DECLARE @return VARCHAR(255)
DECLARE @finished BIT
DECLARE @div INT
DECLARE @rem INT
DECLARE @char CHAR(1)

-- Initialise
SELECT @string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
SELECT @return = CASE WHEN @num <= 0 THEN '0' ELSE '' END
SELECT @finished = CASE WHEN @num <= 0 THEN 1 ELSE 0 END
SELECT @base = CASE WHEN @base < 2 OR @base IS NULL THEN 2 WHEN @base > 36 THEN 36 ELSE @base END

-- 進制轉換迴圈
WHILE @finished = 0
BEGIN

-- 數學運算
SELECT @div = @num / @base
SELECT @rem = @num - (@div * @base)
SELECT @char = SUBSTRING(@string, @rem + 1, 1)
SELECT @return = @char + @return
SELECT @num = @div

-- 沒有值處理?
IF @num = 0 SELECT @finished = 1

END

-- 回傳結果
RETURN @return

END
GO


C#



  public static string DecimalToArbitrarySystem(long decimalNumber, int radix)
{
const int BitsInLong = 64;
const string Digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

if (radix < 2 || radix > Digits.Length)
throw new ArgumentException("The radix must be >= 2 and <= " + Digits.Length.ToString());

if (decimalNumber == 0)
return "0";

int index = BitsInLong - 1;
long currentNumber = Math.Abs(decimalNumber);
char[] charArray = new char[BitsInLong];

while (currentNumber != 0)
{
int remainder = (int)(currentNumber % radix);
charArray[index--] = Digits[remainder];
currentNumber = currentNumber / radix;
}

string result = new String(charArray, index + 1, BitsInLong - index - 1);
if (decimalNumber < 0)
{
result = "-" + result;
}

return result;
}

沒有留言:

張貼留言