Technical Article

Convert integers from decimal to binary display.

,

This script converts numbers from decimals to their binary equivalent.

/*
Created:     DPR 2005
Description: Convert integers (type 'int') from decimal to binary notation.
*/
create function xInt2Binary (
  @val int)
returns char(39) as
begin
  declare @rtnVal char(39)
  declare @i      smallint

  set @rtnVal = ''

  -- test bits up to sign bit
  set @i = 0
  while @i < 31
    begin
      if @val & power(2, @i) > 0
        set @rtnVal = '1' +  @rtnVal
      else
        set @rtnVal = '0' + @rtnVal

      set @i = @i + 1

      -- output in blocks of four bits
      if @i%4 = 0
        set @rtnVal = ' ' + @rtnVal
    end

  -- add sign bit
  if @val >= 0
    set @rtnVal = '0' + @rtnVal
  else
    set @rtnVal = '1' + @rtnVal

  return (@rtnVal)
end

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating