DEV Community

Discussion on: What is an easy bit manipulation technique I can learn in 5 minutes?

Collapse
 
ahferroin7 profile image
Austin S. Hemmelgarn

Ok, here's a neat trick in C to swap the contents of two variables without a temporary variable:

x ^= y
y ^= x
x ^= y

The exact theory behind this is a bit tricky to understand through formal explanation, but is pretty easy to understand by running through it with concrete numbers:

  • Start with X = 84 (0x54 or 0b01010100) and Y = 39 (0x27 or 0b00100111).
  • The first line updates X to a value of 115 (0x73 or 0b01110011).
  • The second line updates Y to a value of 84 (0x54 or 0b01010100).
  • The final line then updates X to a value of 39 (0x27 or 0b00100111).

This has limited practical value today because memory is cheap, but is still sometimes used in code for microcontrollers that have very limited memory. It actually works in any language that supports bitwise XOR and has the same rules as C for bit width. Theoretically the variables don't even have to be the same type, just the same bit width, though C makes you use type casting if they aren't the same type.

Collapse
 
pandaquests profile image
Panda Quests

This is awesome

Collapse
 
lquenti profile image
Lars Quentin

No, it is actually awful please never even think about using it. Modern compiler try to infer semantics, and

X temp = var1;
var1 = var2;
var2 = temp;

is such a known pattern that compiler know that this is a variable switch so theyll optimize it anyways.

And you can read it worse.