1

I have 7 bit binary data stored in a SQL Server database as varchar. This 7 bit binary data ultimately needs to be converted into an int. I was attempting to take this binary string and then convert to varbinary and then convert to integer. The cast to varbinary can accept a hex string, but I'm unable to find a way for this cast to accept a binary string.

Example strings:

0000010
0000100
0001001

These should convert to:

2
4
9

I could create a CLR function to call a C# function, but I was hoping to do this all in T-SQL.

1
  • just create a table with the 128 possible strings and values and look it up from there Commented Apr 27, 2021 at 17:32

1 Answer 1

2

Convertion by hand

select id, sum(cast(substring(str, 7-p.pos, 1) as int) * power(2, p.pos)) val
from (
  SELECT 1 id, '0001001' str union all
  SELECT 2 id, '0001011' str
) t
cross apply (
  values 
     (0)
    ,(1)
    ,(2)
    ,(3)
    ,(4)
    ,(5)
    ,(6)
  ) p(pos)
group by id
Sign up to request clarification or add additional context in comments.

1 Comment

Genius! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.