SQL function to Decode a Bitmask?

  • Does anyone have a script / sp / function that will decode a bitmask into a number?

     

     



    A.J.
    DBA with an attitude

  • I just wrote this, but it should work.

     

     

    create function dbo.fnBitMaskToInt

    (

     @Bits varchar(64)

    )

    returns int

    as

    begin

     declare @Value int

     declare @i int

     declare @length int

     declare @CurChar char

     set @value = 0

     

     set @length = len(@bits)

     set @i = 0

     while @i < @length

     begin

      set @curchar = left(@bits,1)

      set @bits = right(@bits,len(@bits)-1) 

     

      if @curchar = '1'

      begin

       set @value = @value + power(2,@i)

      end

      set @i = @i + 1

     end

     return @value

    end

    If the phone doesn't ring...It's me.

  • Declare @STR varchar(40)

    Set @STR = '0011111111111111'

    create function dbo.udf_FromBitmToInt( @STR varchar(64))

    returns bigint

    as

    begin

     declare @cntr int, @result bigint, @len int

     -- init vars

     Select @len = len(@str), @cntr = len(@str), @result =0

     

     While @cntr > 0

     begin

     if Substring(@str, @cntr,1) = '1'

      set @result = @result + power(2, @len - @cntr )

     

     set @cntr = @cntr - 1

     end

     

     return @result

    end

    HTH

     


    * Noel

  • Gracias Amigos.



    A.J.
    DBA with an attitude

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply