DEV Community

Panda Quests
Panda Quests

Posted on

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

Top comments (8)

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.

Collapse
 
love profile image
love

Not sure if this qualifies but a lot of people don't know about the f-string feature in python. You can do for example :

import os
file = 'test.txt'
print(f"File is located at: {os.path.realpath(file)}")

Collapse
 
pandaquests profile image
Panda Quests

What has this to do with bit manipulation?

Collapse
 
love profile image
love

Lol I think I totally read over your question too quickly or it must have been very late when I wrote that.

Collapse
 
pandaquests profile image
Panda Quests

Something like this:
function isOdd (num) {
return (num & 1) === 1;
}

the 1 (in num & 1) is used as a mask to check whether the number num is odd or not. If the last bit is set to 1 we know it is odd otherwise it is not odd.