clear markdown compare help best fiddles feedback dbanow.uk a leap of faith?
clear markdown donate comments/suggestions/bugs a leap of faith? bible365 diddy dollings
By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0. 1716912 fiddles created (23828 in the last week).

CREATE FUNCTION fnGetBitsForMask (@Mask INT) RETURNS TABLE AS RETURN WITH BitwiseValues AS ( SELECT CAST(1 AS INT) AS RowNumber, CAST(0 AS INT) AS BitValue UNION ALL SELECT b1.RowNumber+1 AS RowNumber, POWER(2, b1.RowNumber-1) AS BitValue FROM BitwiseValues b1 WHERE b1.RowNumber < 30 ) SELECT b.BitValue FROM BitwiseValues b CROSS JOIN (SELECT @Mask AS Mask) m WHERE b.BitValue & m.Mask > 0
 hidden batch(es)


WITH Mask AS ( SELECT 0 AS Val UNION ALL SELECT Val + 1 FROM Mask WHERE Val < 31 ) SELECT m.Val AS Mask, gbfm.BitValue FROM Mask m CROSS APPLY dbo.fnGetBitsForMask(m.Val) gbfm ORDER BY 1, 2;
Mask BitValue
1 1
2 2
3 1
3 2
4 4
5 1
5 4
6 2
6 4
7 1
7 2
7 4
8 8
9 1
9 8
10 2
10 8
11 1
11 2
11 8
12 4
12 8
13 1
13 4
13 8
14 2
14 4
14 8
15 1
15 2
15 4
15 8
16 16
17 1
17 16
18 2
18 16
19 1
19 2
19 16
20 4
20 16
21 1
21 4
21 16
22 2
22 4
22 16
23 1
23 2
23 4
23 16
24 8
24 16
25 1
25 8
25 16
26 2
26 8
26 16
27 1
27 2
27 8
27 16
28 4
28 8
28 16
29 1
29 4
29 8
29 16
30 2
30 4
30 8
30 16
31 1
31 2
31 4
31 8
31 16
 hidden batch(es)


WITH Mask AS ( SELECT 0 AS Val UNION ALL SELECT Val + 1 FROM Mask WHERE Val < 31 ), Map AS ( SELECT m.Val AS Mask, gbfm.BitValue, 1 as One FROM Mask m CROSS APPLY dbo.fnGetBitsForMask(m.Val) gbfm ) SELECT pvt.Mask, pvt.[16], pvt.[8], pvt.[4], pvt.[2], pvt.[1], CONCAT( [16], [8], [4], [2], [1]) AS Bin FROM Map AS m PIVOT ( COUNT(m.One) FOR m.BitValue IN ( [1], [2], [4], [8], [16] ) ) pvt ORDER BY 1;
Mask 16 8 4 2 1 Bin
1 0 0 0 0 1 00001
2 0 0 0 1 0 00010
3 0 0 0 1 1 00011
4 0 0 1 0 0 00100
5 0 0 1 0 1 00101
6 0 0 1 1 0 00110
7 0 0 1 1 1 00111
8 0 1 0 0 0 01000
9 0 1 0 0 1 01001
10 0 1 0 1 0 01010
11 0 1 0 1 1 01011
12 0 1 1 0 0 01100
13 0 1 1 0 1 01101
14 0 1 1 1 0 01110
15 0 1 1 1 1 01111
16 1 0 0 0 0 10000
17 1 0 0 0 1 10001
18 1 0 0 1 0 10010
19 1 0 0 1 1 10011
20 1 0 1 0 0 10100
21 1 0 1 0 1 10101
22 1 0 1 1 0 10110
23 1 0 1 1 1 10111
24 1 1 0 0 0 11000
25 1 1 0 0 1 11001
26 1 1 0 1 0 11010
27 1 1 0 1 1 11011
28 1 1 1 0 0 11100
29 1 1 1 0 1 11101
30 1 1 1 1 0 11110
31 1 1 1 1 1 11111
 hidden batch(es)