【请教】字符串位运算问题...

两个字符串:
10000000000100000000000000000000000000000000000000000000000000000000000010

01000010000100001000000000000000000000000000000000000000000000000000000000

现在要将它们当做二进制数据进行位运算,该如何去做...
--------------------------------------------------------------
&(按位 AND)
¦(按位 OR)
^(按位互斥 OR)
---------------------------------------------------------------

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_str]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_str]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[序数表]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [序数表]
GO

--为了效率,所以要一个辅助表配合
select top 8000 id=identity(int,1,1) into 序数表
from syscolumns a,syscolumns b
alter table 序数表 add constraint pk_id_序数表 primary key(id)
go

--处理函数
create function f_str(
@str1 varchar(8000), --字符串1
@str2 varchar(8000), --字符串2
@str char(1) --操作符^& ¦
)returns varchar(8000)
as
begin
declare @re varchar(8000)
set @re=''
if len(@str1)<>len(@str2)
if len(@str1)>len(@str2)
set @str2=replicate('0',len(@str1)-len(@str2))+@str2
else
set @str1=replicate('0',len(@str2)-len(@str1))+@str1

if @str='^'
select @re=@re+case substring(@str1,id,1) when substring(@str2,id,1) then '0' else '1' end
from 序数表
where id<=len(@str1)
else if @str=' ¦'
select @re=@re+case substring(@str1,id,1)+substring(@str2,id,1) when '00' then '0' else '1' end
from 序数表
where id<=len(@str1)
else
select @re=@re+case substring(@str1,id,1)+substring(@str2,id,1) when '11' then '1' else '0' end
from 序数表
where id<=len(@str1)
return(@re)
end
go

--调用
select dbo.f_str('001','100','&')

---------------------------------------------------------------

--其中op=^ ¦&的其中一个,调用方法select dbo.getit('00001','0000','&')
CREATE FUNCTION getit(@t1 varchar(8000),@t2 varchar(8000),@op varchar(1))
RETURNS varchar(8000)
AS
BEGIN
declare @result varchar(8000)
declare @s1 varchar(1),@s2 varchar(2)
declare @t1_len int, @t2_len int ,@t_len int
set @result=''
set @t1_len=len(@t1)
set @t2_len=len(@t2)
set @t_len=@t1_len

if @t2_len<@t1_len
begin
set @t_len=@t2_len
set @result=substring(@t1,1,@t1_len-@t2_len)
end
else
set @result=substring(@t2,1,@t2_len-@t1_len)

while (@t_len>0)
begin
set @s1=substring(@t1,@t1_len-@t_len+1,1)
set @s2=substring(@t2,@t2_len-@t_len+1,1)

if (@op=' ¦')
begin
if (@s1='1' or @s2='1' )
set @result=@result + '1'
else
set @result=@result + '0'
end

if (@op='&')
begin
if (@s1='0' or @s2='0' )
set @result=@result + '0'
else
set @result=@result + '1'
end

if (@op='^')
begin
if ( (@s1='1' and @s2='1' ) or (@s1='0' and @s2='0') )
set @result=@result + '0'
else
set @result=@result + '1'
end

set @t_len=@t_len-1
end

return @result
END

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus