简体   繁体   中英

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 parentheses!

~() is actually two things:

  1. (uint32_t) is a cast.
  2. ~ 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 in CST_IEc after it has been cast to uint32_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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM