简体   繁体   中英

What does (a ^ (1 << b)) actually do, in a language like C++?

I'm looking at this function,

int func(int a, int b){
    return (a ^ (1 << b)); 
}

What is actually going on? I understand that it's basically saying, " a XOR (2^b) ", that is, a xor 2 to the power of b. But beyond that what is actually happening, and why? I guess I'm looking for some sort of pattern in this formula.

This particular expression toggles the b-th bit of a.

This could be useful for example if you want to treat your int as a boolean array (or a bitmask), and negate the entry at position b.

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