I'm a Systems Reliability and DevOps engineer for Netdata Inc. When not working, I enjoy studying linguistics and history, playing video games, and cooking all kinds of international cuisine.
Ok, here's a neat trick in C to swap the contents of two variables without a temporary variable:
x^=yy^=xx^=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.
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.
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (8)
Ok, here's a neat trick in C to swap the contents of two variables without a temporary variable:
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:
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.
This is awesome
No, it is actually awful please never even think about using it. Modern compiler try to infer semantics, and
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.
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)}")
What has this to do with bit manipulation?
Lol I think I totally read over your question too quickly or it must have been very late when I wrote that.
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.