What does ~ mean in C++?
Specifically, could you tell me what this line of code does:
int var1 = (var2 + 7) & ~7;
开发者_如何学编程
Thanks
It's bitwise negation. This means that it performs the binary NOT operator on every bit of a number. For example:
int x = 15; // Binary: 00000000 00000000 00000000 00001111
int y = ~x; // Binary: 11111111 11111111 11111111 11110000
When coupled with the & operator it is used for clearing bits. So, in your example it means that the last 3 bits of the result of var2+7
are set to zeroes.
As noted in the comments, it's also used to denote destructors, but that's not the case in your example.
This code rounds up var1 to the closest n*8 number. & ~7 sets last 3 bits to 0, rounding down to 8*n.
It's a bitwise NOT. Not to be confused with logical not (which is !), which flips the logical value (true to false and vice versa). This operator flips every bit in a variable.
7 in binary is 00000111, so ~7 is 11111000 (assuming an eight-bit byte). The code author is using it for bit masking.
The effect of the code, as noted, is to round a value to the next higher multiple of eight. My preferred formulation would be "var1 = (var2 | 7)+1;" but to understand the expression as written, it's most helpful to understand it from the outside in.
Although "&" and "~" are separate operators, with different prioritization rules, the concept of "a = b & ~c;" is a useful one which in a very real sense deserves its own operator (it would allow more sensible integer promotion rules, among other things). Basically, "a = b & ~c;" serves to cancel out any bits in 'b' that are also in 'c' (if 'b' is long and 'c' isn't, because of integer promotion rules, it my cancel higher bits as well). If 'c' is 2^N-1, the expression will cancel out the bottom N bits, which is equivalent to rounding down to the next multiple of 2^N.
The expression as written adds 7 to var2 before rounding the result down to the next multiple of 8. If var2 was a multiple of 8, adding 7 won't quite reach the next higher multiple of 8, but otherwise it will. Thus, the expression as a whole will round up to the next multiple of 8.
Incidentally, my preferred formulation rounds the number up to the next higher value that's just short of a multiple of 8, and then bumps it up to the next multiple. It avoids the repetition of the magic number "7", and in some instruction sets the approach will save code.
精彩评论