sqlsql-server

SQL Server Convert integer to binary string


I was wondering if there was an easy way in SQL to convert an integer to its binary representation and then store it as a varchar.

For example 5 would be converted to "101" and stored as a varchar.


Solution

  • Following could be coded into a function. You would need to trim off leading zeros to meet requirements of your question.

    declare @intvalue int
    set @intvalue=5
    
    declare @vsresult varchar(64)
    declare @inti int
    select @inti = 64, @vsresult = ''
    while @inti>0
      begin
        select @vsresult=convert(char(1), @intvalue % 2)+@vsresult
        select @intvalue = convert(int, (@intvalue / 2)), @inti=@inti-1
      end
    select @vsresult