Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ XOR swap on float values

Is it possible to use XOR swapping algorithm with float values in c++?

However wikipedia says that:

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

but I am bit confused. With this code:

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;
}

it seems to work (at least under gcc), but I am concerned if such a practice is allowed if needed?

like image 676
m.zygmunt Avatar asked May 20 '26 16:05

m.zygmunt


2 Answers

Technically, what you ask is possible but, as clearly commented by IInspectable, it causes UB (Undefined Behaviour).
Anyway, I do suggest you to use std::swap instead, it's a template often specialized for specific data types and designed to do a good job.

like image 54
roalz Avatar answered May 22 '26 05:05

roalz


If int is the same size as float, it is going to work in practice on any reasonable architecture. The memory in the float is a set of bits, you interpret those bits and swap them completely using xor operations. You can then use Those bits as the proper floats again. The quote you refer to only says that the two values you swap need to be of the same type, and both are ints.

However, on some architectures, this can result in a movement between different sorts of registers, or explicitly flushing registers to memory. What you will see on almost any sane architecture with a sane optimizing compiler these days, is that an explicit swap, using std::swap or an expression with a temporary variable, is in fact faster.

I.e. you should write:

float a = 255.33333f;
float b = 0.123023f;
float tmp = a;
a = b;
b = tmp;

or preferably:

float a = 255.33333f;
float b = 0.123023f;
std::swap(a,b);

If the standard library author for your architecture has determined xor swapping to indeed be beneficial, then you should hope that the last form will use it. xor swapping is a typical bad idiom in terms of hiding intent in an unneccesarily arcane implementation. It was only ever efficient in seriously register-starved cases with bad optimizers.

like image 41
cnettel Avatar answered May 22 '26 05:05

cnettel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!