X进制与10进制之间的转换
在网上看到有16进制转为10进制,10转为16进制的方法,我这里做个X进制与10进制之间转换,算法与16<-->10直接的转换算法是相似的。
X进制与10进制之间的转换:
Declare @x nvarchar(1024)
Declare @y int
Declare @sys int --x进制
Set @x='30'
Set @sys=21 --@sys=21表示二十一进制
--x进制转换成10进制
;With
T1 As(
Select
X=Stuff(Reverse(@x),1,1,''),
Y=Convert(int,Case Isnumeric(Right(@x,1)) When 0 Then ASCII(Upper(Right(@x,1)))-55 Else Right(@x,1) End*Power(@sys,0)),
L=Convert(int,1)
Union All
Select
X=Stuff(X,1,1,''),
Y=Convert(int,Case Isnumeric(Left(X,1)) When 0 Then ASCII(Upper(Left(X,1)))-55 Else Left(X,1) End*Power(@sys,L)),
L=L+Convert(int,1)
From T1
Where X>''
)
Select [10进制-->X进制]=SUM(Y) From T1
--10进制换成x进制转
Set @y=32
Set @sys=2 --@sys=2表示二进制
;With
T1 As(
Select
X=Convert(int,@y/@sys),
Y=Convert(nvarchar(1024),Case (@y%@sys)/10 When 0 Then Rtrim(@y%@sys) Else Char(@y%@sys%10+65) End),
L=Convert(int,1)
Union All
Select
X=X/@sys,
Y=Convert(nvarchar(1024),Case (X%@sys)/10 When 0 Then Rtrim(X%@sys) Else Char(X%@sys%10+65) End+Y),
L=Convert(int,L+1)
From T1 Where X>0
)
Select Top 1 [x进制-->10进制]=Y From T1 Order By L Desc
Declare @y int
Declare @sys int --x进制
Set @x='30'
Set @sys=21 --@sys=21表示二十一进制
--x进制转换成10进制
;With
T1 As(
Select
X=Stuff(Reverse(@x),1,1,''),
Y=Convert(int,Case Isnumeric(Right(@x,1)) When 0 Then ASCII(Upper(Right(@x,1)))-55 Else Right(@x,1) End*Power(@sys,0)),
L=Convert(int,1)
Union All
Select
X=Stuff(X,1,1,''),
Y=Convert(int,Case Isnumeric(Left(X,1)) When 0 Then ASCII(Upper(Left(X,1)))-55 Else Left(X,1) End*Power(@sys,L)),
L=L+Convert(int,1)
From T1
Where X>''
)
Select [10进制-->X进制]=SUM(Y) From T1
--10进制换成x进制转
Set @y=32
Set @sys=2 --@sys=2表示二进制
;With
T1 As(
Select
X=Convert(int,@y/@sys),
Y=Convert(nvarchar(1024),Case (@y%@sys)/10 When 0 Then Rtrim(@y%@sys) Else Char(@y%@sys%10+65) End),
L=Convert(int,1)
Union All
Select
X=X/@sys,
Y=Convert(nvarchar(1024),Case (X%@sys)/10 When 0 Then Rtrim(X%@sys) Else Char(X%@sys%10+65) End+Y),
L=Convert(int,L+1)
From T1 Where X>0
)
Select Top 1 [x进制-->10进制]=Y From T1 Order By L Desc
结果:
10进制-->X进制
-----------
63
(1 行受影响)
x进制-->10进制
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
100000
(1 行受影响)