Performs a bitwise logical NOT operation on an integer value.
Transact-SQL Syntax Conventions
~ expression
Is any valid expression of any one of the data types of the integer data type category, the bit, or the binary or varbinary data types. expression is treated as a binary number for the bitwise operation.
The ~ bitwise operator performs a bitwise logical NOT for the expression, taking each bit in turn. If expression has a value of 0, the bits in the result set are set to 1; otherwise, the bit in the result is cleared to a value of 0. In other words, ones are changed to zeros and zeros are changed to ones.
int if the input values are int.
smallint if the input values are smallint.
tinyint if the input values are tinyint.
bit if the input values are bit.
The following example creates a table using the int data type to store the values and inserts the two values into one row.
USE tempdb; GO IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'bitwise') DROP TABLE bitwise; GO CREATE TABLE bitwise ( a_int_value int NOT NULL, b_int_value int NOT NULL ); GO INSERT bitwise VALUES (170, 75); GO
The following query performs the bitwise NOT on the a_int_value and b_int_value columns.
a_int_value
b_int_value
USE tempdb; GO SELECT ~ a_int_value, ~ b_int_value FROM bitwise;
Here is the result set:
--- --- -171 -76 (1 row(s) affected)
The binary representation of 170 (a_int_value or A) is 0000 0000 1010 1010. Performing the bitwise NOT operation on this value produces the binary result 1111 1111 0101 0101, which is decimal -171. The binary representation for 75 is 0000 0000 0100 1011. Performing the bitwise NOT operation produces 1111 1111 1011 0100, which is decimal -76.
A
0000 0000 1010 1010
1111 1111 0101 0101
0000 0000 0100 1011
1111 1111 1011 0100
(~A) 0000 0000 1010 1010 ------------------- 1111 1111 0101 0101 (~B) 0000 0000 0100 1011 ------------------- 1111 1111 1011 0100