What does the tilde mean in an expression? [duplicate]

Possible Duplicate:
What is the tilde (~) in a C# enumeration?

I found the following bit of code on a this MSDN page.

(((Width * Planes * BitCount + 31) & ~31) / 8) * abs(Height)

This does indeed compile in C# visual studio 2010. What exactly is the tilde "~" doing in front of the number 31? I've never seen this syntax in an expression before.


~ - bitwise NOT operator, basically invert bits

31 in binary format is 11111, so ~31 == 11111111111111111111111111100000, or 0xFFFFFFE0 hexadecimal.


That is the bitwise complement operator, also known as bitwise negation.


It is the bitwise complement operator.

Basically, it flips the bits:

0xffff0000 == ~0x0000ffff

In the code you have posted, doing & ~31 ensures the last 5 bits are 0 (bitwise and of the complement of 11111 which is 00000).


You turn to your handy copy of ISO/IEC 23270:2006 — Information technology — Programming languages — C# and turn to §14.6.4 of the holy write. There you will find:


14.6.4 Bitwise complement operator

For an operation of the form ~x, unary operator overload resolution (§14.2.3) is applied to select a specific operator implementation. The operand is converted to the parameter type of the selected operator, and the type of the result is the return type of the operator. The predefined bitwise complement operators are:

int   operator ~( int   x ) ;
uint  operator ~( uint  x ) ;
long  operator ~( long  x ) ;
ulong operator ~( ulong x ) ;

For each of these operators, the result of the operation is the bitwise complement of x.

Every enumeration type E implicitly provides the following bitwise complement operator:

E operator ~(E x);

The result of evaluating ~x, where x is an expression of an enumeration type E with an underlying type U, is exactly the same as evaluating unchecked((E)(~(U)x)). This operator is only considered by unary operator overload resolution when the operand type is the enum type E (§14.2.3).

Lifted (§14.2.7) forms of the unlifted predefined bitwise complement operators defined above are also predefined.


In your case ~31 is the same as ~ 0x0000001F. The bitwise complenent of 0x0000001F is 0xFFFFFFE0. Why they wouldn't just write the actual mask they wanted is beyond me.


This is the bitwise complement operator - it just makes all 0 bits into 1s and vice versa... see MSDN reference.

In your specific case it just creates (31 = 0x1F):

~0x1F = 0xFFFFFFE0

It is used with the bitwise and (&) and thus bascially it cancels out the last 5 bits.