sqlserver怎么进行整数的移位运算
请教sqlserver怎么进行整数的移位运算,左移和右移
[解决办法]
use tempdb;
GO
--逻辑左移函数
--@n为左移的位数 取值 [0,32]
create function dbo.fShl(@int int,@n tinyint)
returns int
begin
if @n<0 or @n>32 return 0;
declare @bigint binary(8)
set @bigint = @int
while @n>0
begin
set @bigint=@bigint*cast(2 as bigint)
set @n=@n-1
end
return @bigint & -1
end
GO
--测试
declare @testint int
set @testint=1234123123
select cast(1234123123 as binary(4)) --'移位前 '
select cast(dbo.fShl(1234123123,8) as binary(4)) --'逻辑左移8位后'
GO
--结果:
--移位前
----------
--0x498F3973
--逻辑左移8位后
----------
--0x8F397300
--*****----*****----*****----*****----*****----*****--
--逻辑右移函数
--@n为右移的位数 取值 [0,32]
create function dbo.fShr(@int int,@n tinyint)
returns int
begin
if @n<0 or @n>32 return 0;
declare @bigint binary(8)
set @bigint = @int
while @n>0
begin
set @bigint=@bigint/cast(2 as bigint)
set @n=@n-1
end
return @bigint & -1
end
GO
declare @testint int
set @testint=1234123123
select cast(1234123123 as binary(4)) --'移位前 '
select cast(dbo.fShr(1234123123,8) as binary(4)) --'逻辑右移8位后'
GO
--结果:
--移位前
----------
--0x498F3973
--逻辑右移8位后
----------
--0x00498F39
use tempdb;
GO
--逻辑左移函数
--@n为左移的位数 取值 [0,32]
create function dbo.fShl(@int int,@n tinyint)
returns int
begin
if @n<0 or @n>32 return 0;
declare @bigint binary(8)
set @bigint = @int
while @n>0
begin
set @bigint=@bigint*cast(2 as bigint)
set @n=@n-1
end
return @bigint & -1
end
GO
--测试
declare @testint int
set @testint=1234123123
select cast(1234123123 as binary(4)) --'移位前 '
select cast(dbo.fShl(1234123123,8) as binary(4)) --'逻辑左移8位后'
GO
--结果:
--移位前
----------
--0x498F3973
--逻辑左移8位后
----------
--0x8F397300
--逻辑右移函数
--@n为右移的位数 取值 [0,32]
create function dbo.fShr(@int int,@n tinyint)
returns int
begin
if @n<0 or @n>32 return 0;
declare @bigint binary(8)
set @bigint = @int
while @n>0
begin
set @bigint=@bigint/cast(2 as bigint)
set @n=@n-1
end
return @bigint & -1
end
GO
declare @testint int
set @testint=1234123123
select cast(1234123123 as binary(4)) --'移位前 '
select cast(dbo.fShr(1234123123,8) as binary(4)) --'逻辑右移8位后'
GO
--结果:
--移位前
----------
--0x498F3973
--逻辑右移8位后
----------
--0x00498F39