Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing a bitwise sum

As part of a complex aggregate I want to know the bitwise sum of some data, i.e. if I have rows with values 1,1,1,2,2,8 the bitwise sum is 11. In this case the values are all exact powers of two (single bits), so I can hack around it by grouping and summing over the groups (obviously this example is a bit tortured compared to the real query):

select SUM(y.test)
from (
    select x.test
    from ( -- garbage test data
        select 1 as [test]
        union all select 1
        union all select 1
        union all select 2
        union all select 2
        union all select 8) x
group by x.test) y

but is there a clean way to perform a bitwise sum in [T]SQL?

like image 873
Marc Gravell Avatar asked Dec 14 '10 11:12

Marc Gravell


People also ask

How do you do bitwise sum?

Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing AND (&) of two bits. Above is simple Half Adder logic that can be used to add 2 single bits. We can extend this logic for integers.

What is or sum bitwise?

Given an array “arr[0..n-1]” of integers. The task is to calculate the sum of Bitwise OR of all pairs, i.e. calculate the sum of “arr[i] | arr[j]” for all the pairs in the given array where i < j. Here '|' is a bitwise OR operator.

How do you add two binary numbers using bitwise operators?

Sum of two bits can be performed using the XOR ^ operator and carry bit can be obtained by using AND & operator. Provided a and b don't have set bits at the same position, then using ^ operator gives the sum of a and b .

Is bitwise or and addition same?

Addition and bit-wise or would be the same as bit-wise or would include any bits in either, and normal addition would do exactly the same given the mutually exclusive nature of your bits.


2 Answers

You have the operator | which performs bitwise or for 2 operands. It is possible to solve your problem using a cursor and this operator.

Edit yes I mixed up and and or, fixed.

like image 175
bernd_k Avatar answered Sep 22 '22 09:09

bernd_k


If all of your test values are single bits as in your example (1, 2, 8) - simply use SUM(DISTINCT col) in your query.

Hope that helps.

(For reference: http://msdn.microsoft.com/en-us/library/ms187810.aspx)

like image 36
Kieren Johnstone Avatar answered Sep 18 '22 09:09

Kieren Johnstone