3 ms·
As much as I love bit manipulation, I have to say that most (not all) of them don't provide any real performance gain for C/C++ code (only some geeky satisfacti
by bhavin 16y ago
As much as I love bit manipulation, I have to say that most (not all) of them don't provide any real performance gain for C/C++ code (only some geeky satisfaction of writing difficult to interpret code!)..
e.g. with any decent compiler...
* if ((x & 1) == 0) performs same as, if ((x % 2) == 0)
* if (x & (1<<n)) same as, if (x% (pow(2,n)))
so on..
on the other hand, i find bit operations really handy when the variables in question are to be treated as separate bits than normal base-10..
- deleted 16y ago[deleted]
- alexgartrell 16y agox & (1<<n) is not the same as (x % pow(2, n)) Take x = 2 and n = 1 x & (1 << n) = 0b10 & 0b10 = 0b10 x % pow(2, n) = 2 % 2 = 0 = 0b0 0b0 /= 0b10 fwiw, you were actually looking for (x & ((1 << n) - 1)) = (x % pow(2, n)) That aside, you're absolutely right. Using bit ops is almost always a bad idea. It turns a simple store (to a byte-addressed memory address) into a read, manipulate, and store (to a bit within a byte-addressed memory address) which can have pretty bad side affects in any concurrent environment.
- wingo 16y agoAgreed regarding modulo, but `pow' returns a floating-point number.
- bhavin 16y agosorry, what i meant there wasn't literally pow function per se, but a function which does the job..