SQL Server BIT_COUNT

In this tutorial, we will learn how to use the BIT_COUNT function in SQL Server. This function allows us to determine the number of bits set to 1 in a given input.

Let us dive in.

The following shows the function syntax and accepted arguments:

BIT_COUNT ( expression_value )

The function accepts one argument.

  1. expression_value – this parameter defines the value to be evaluated. The value must be of int or binary data type.

The function will then return a bigint type representing the number of bits set to 1 in the given expression_value.

The function does not cast the given input preceding counting the number of bits. The same number can have different bits set to 1 in its binary representation.

Examples

The following example represents a simple usage of the BIT_COUNT function in SQL Server:

select bit_count(0010111000),
bit_count(1001111001),
bit_count(0010111001),
bit_count(0001101011),
bit_count(0111000111);

This should return the number of bits set to 1 in each input as shown below:

4 6 5 4 6

You can also calculate the number of bits for a binary value as provided below:

SELECT BIT_COUNT ( 0xabcdef );

Output:

2

Conclusion

This article described the usage of the BIT_COUNT() function in SQL Server. Remember that in the initial implementation, DQ functionality for bit manipulation functions within linked server or ad hoc queries are not supported at the time of the writing.



from https://ift.tt/GfmDgK9

Post a Comment

0 Comments