I'm not sure how logical this project is, but it seemed interesting to do this without looping. It was fun.
declare @b-2 bigint = 31;
declare @out varbinary(128) = 0x;
-- simple inline tally table
with cteTen as
( select N from (values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) as t(N) ),
cteNums as
( select N = 0
union all
selecttop (63) -- the 64th bit would be bigger than a bigint max value
N = row_number() over(order by (select null))
from cteTen as cte1
cross join cteTen as cte2 ),
-- the meat of the query
cteInit as
( selectcte.N
,ValThis = power(convert(decimal(20,0), 2), N)
,ValNext = power(convert(decimal(20,0), 2), N + 1)
from cteNums as cte )
select@out = @out + convert(varbinary(1), case when (@b - (floor(@b / cte.ValNext)) * cte.ValNext) >= cte.ValThis then 1 else 0 end)
from cteInit as cte
where cte.ValThis <= @b-2
order by cte.N desc;
select @out;
This is verified to work with the largest possible bigint. I did not code it with negative numbers in mind.