What does ~(uint32_t) mean?
I'm reading a bit of C code in an OS kernel that says
x & ~(uint32_t)CST_IEc;
What does the ~()
mean? It's a tilde followed by parent开发者_运维知识库heses!
~()
is actually two things:
(uint32_t)
is a cast.~
is a bitwise complement operator.
A few more parantheses to clearify evaluation order:
(x & (~((uint32_t)CST_IEc)))
First CST_IEc
is casted into a uint32_t
then it is bitwise negated with ~
before being bitwise anded with x
through &
.
You are interpreting the operator precedence incorrectly. The cast (uint32_t)CST_IEc
is done first and ~
happens after that. Take a look at an operator precedence chart for help.
- The
(uint32_t)
bit is a cast to a type of unsigned int (32 bits), - the
~
means bitwise not (or complement), so it reverses the bits inCST_IEc
after it has been cast touint32_t
.
(uint32_t)CST_IEc; //casting CST_IEc to uint32_t
~( ) //taking one's complement
You need to read the expression slightly differently:
(uint32_t)CST_IEc
This converts the value CST_IEc
into a 32-bit unsigned integer.
~(uint32_t)CST_IEc;
The ~
then does a bit-wise inversion of the value; each one bit becomes a zero and each zero bit becomes a one.
The whole expression then does:
x & ~(uint32_t)CST_IEc;
This means that the result contains the bits in x
except for the bits implied by the value of CST_IEc
; those are zeroed.
So, if CST_IEc
was, for sake of example, 0x0F00, and the input value of x
was 0x12345678, the result would be 0x12345078.
Isn't (uint32_t) a type cast?
~ is bitwise NOT
精彩评论