Wednesday, June 11, 2014

Find the 2’s Compliment for the binary number in the SQL SERVER

2’s Complete Example

Declare @MainChar Varchar(Max),@ReveL Varchar(Max),@ReveR Varchar(Max)
set @MainChar='0010010010'
if(len(replace(@MainChar,'0',''))>0)
begin
set @MainChar=replace(replace(replace(@MainChar,'1','a'),'0','1'),'a','0')
set @MainChar=REVERSE(@MainChar)
set @ReveL=replace(replace(replace(SUBSTRING(@MainChar,1,CHARINDEX('0', @MainChar)),'1','a'),'0','1'),'a','0');
set @ReveR=SUBSTRING(@MainChar,CHARINDEX('0', @MainChar)+1,Len(@MainChar)-(CHARINDEX('0', @MainChar)))
select REVERSE(@ReveL+@ReveR)
end
else
select @MainChar

output

1111011110

No comments:

Post a Comment