gpt4 book ai didi

C++ XOR 交换浮点值

转载 作者:太空狗 更新时间:2023-10-29 23:43:45 25 4
gpt4 key购买 nike

是否可以在 C++ 中对浮点值使用 XOR 交换算法?

但是维基百科是这样说的:

XOR bitwise operation to swap values of distinct variables having the same data type

但我有点困惑。使用此代码:

void xorSwap (int* x, int* y) {
*x ^= *y;
*y ^= *x;
*x ^= *y;
}

int main() {

float a = 255.33333f;
float b = 0.123023f;
xorSwap(reinterpret_cast<int*>(&a), reinterpret_cast<int*>(&b));
std::cout << a << ", " << b << "\n";

return 0;
}

它似乎可行(至少在 gcc 下是这样),但我担心如果需要,是否允许这种做法?

最佳答案

从技术上讲,您问的可能的,但是,正如 IInspectable 明确评论的那样,它会导致 UB(未定义行为)。
无论如何,我建议你使用 std::swap相反,它是一个模板,通常专门用于特定的数据类型,旨在做好工作。

关于C++ XOR 交换浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42069457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com