Skip to content
Advertisement

Calculate Count of true bits in binary type with t-sql

I need to find how many true bit exists in my binary value.

example:

input: 0001101    output:3
input: 1111001    output:5

Advertisement

Answer

DECLARE @BinaryVariable2 VARBINARY(10);

SET @BinaryVariable2 = 60; -- binary value is 111100

DECLARE @counter int  = 0

WHILE @BinaryVariable2 > 0 
  SELECT @counter +=@BinaryVariable2 % 2,  @BinaryVariable2 /= 2

SELECT @counter

Result:

4
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement