相关疑难解决方法(0)

XOR变量交换如何工作?

有人可以向我解释如何在没有临时变量的情况下对两个变量进行XOR交换吗?

void xorSwap (int *x, int *y)
{
    if (x != y) {
        *x ^= *y;
        *y ^= *x;
        *x ^= *y;
    }
}
Run Code Online (Sandbox Code Playgroud)

我明白它做了什么,但有人可以告诉我它是如何工作的逻辑吗?

language-agnostic bit-manipulation xor

68
推荐指数
8
解决办法
2万
查看次数

在不使用临时变量的情况下交换两个变量

我希望能够在不使用C#中的临时变量的情况下交换两个变量.可以这样做吗?

decimal startAngle = Convert.ToDecimal(159.9);
decimal stopAngle = Convert.ToDecimal(355.87);

// Swap each:
//   startAngle becomes: 355.87
//   stopAngle becomes: 159.9
Run Code Online (Sandbox Code Playgroud)

c# algorithm swap

63
推荐指数
15
解决办法
15万
查看次数

如何在C#中自动交换2个整数?

什么(如果有的话)是x86 asm xchg指令的C#等价物?

有了这个命令,哪个imo是一个真正的交换(不像Interlocked.Exchange),我可以简单地自动交换两个int,这就是我真正想做的事情.

更新:

示例代码基于我的建议.变量后缀"_V"被装饰为volatile:

// PART 3 - process links
// prepare the new Producer
address.ProducerNew.WorkMask_V = 0;
// copy the current LinkMask
address.ProducerNew.LinkMask_V = address.Producer.LinkMask_V;
// has another (any) thread indicated it dropped its message link from this thread?
if (this.routerEmptyMask[address.ID] != 0)
{
  // allow all other bits to remain on (i.e. turn off now defunct links)
  address.ProducerNew.LinkMask_V &= ~this.routerEmptyMask[address.ID];
  // reset
  this.routerEmptyMask[address.ID] = 0;
}
// PART 4 - swap
address.ProducerNew = …
Run Code Online (Sandbox Code Playgroud)

.net c# atomic

26
推荐指数
5
解决办法
8216
查看次数

标签 统计

c# ×2

.net ×1

algorithm ×1

atomic ×1

bit-manipulation ×1

language-agnostic ×1

swap ×1

xor ×1