简体   繁体   English

在像 C++ 这样的语言中 (a ^ (1 << b)) 实际上做了什么?

[英]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.我知道它基本上是在说“a XOR (2^b)”,即 b 的幂的异或 2。 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.这个特殊的表达式切换 a 的第 b 位。

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.例如,如果您想将int视为布尔数组(或位掩码),并否定位置 b 处的条目,这可能很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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