Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefit of writing (1<<24 - 1) instead of FFFFFF?

Tags:

c

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

like image 446
drolex Avatar asked May 25 '11 13:05

drolex


4 Answers

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.

like image 164
Tomas Avatar answered Nov 17 '22 00:11

Tomas


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.

like image 8
NPE Avatar answered Nov 17 '22 00:11

NPE


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.

like image 2
Simone Avatar answered Nov 17 '22 01:11

Simone


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;
}
like image 2
pmg Avatar answered Nov 17 '22 02:11

pmg