I have a piece of code in C with the following:
a = b & ((1<<24) - 1);
If I am not mistaking, this is equivalent to:
a = b & 0xFFFFFF;
What is the benefit in terms of performance to write the first one? For me it is more complicated to read, but I suppose the guy who wrote that had a better C background than I have.
Thanks
There is no difference in performance since the compiler will perform the calculation for you.
The first option may be used to explicitly clarify that you are using 24 set bits. This is harder to count in the second option.
In all likelihood, there isn't any performance difference since the compiler will figure out that ((1<<24) - 1)
is a constant expression, and will evaluate it at compile time.
We can only speculate about why the original author of the code chose to write it the way they did. Perhaps they thought it better expressed the intent ("mask out all but the 24 least significant bits of b
").
If that was their reasoning, I personally would tend to agree with them.
I can't see any benefit from the performance point of view, as aix says.
To me, anyway, it appears clearer in the first version better communicates that the constant value is 2^24-1 than the latter form. Of course, I guess this is just an opinion.
If it isn't part of a larger block of code, I like your use of 0xFFFFFF
better.
But, it can conceivably be part of a group of similar statements. Then the shift version is (arguably) better.
switch (binaryprefix) {
default: a = 0; break;
case DECABIN: a = b & ((1 << 1) - 1); break;
case HECTOBIN: a = b & ((1 << 2) - 1); break;
case KILOBIN: a = b & ((1 << 3) - 1); break;
case MEGABIN: a = b & ((1 << 6) - 1); break;
/* ... */
case ZETTABIN: a = b & ((1 << 21) - 1); break;
case YOTTABIN: a = b & ((1 << 24) - 1); break;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With