I need to make the last 5 bits of the unsigned int become zero(1111_1111 to 1110_0000)

There are two solution

``````unsigned int number = 0xFFFF;
unsigned int temp_one = number & (~0x1F);
unsigned int temp_two = number >> 5 << 5;``````

which one is faster?
I write a small program to measure the time
But it is always 0 after optimize

Thanks a lot

## All 4 Replies

I write a small program to measure the time

Why don't you put the solution in a loop. Loop it some 100000... times, so that your program will give you some number. Do it separately for both solutions.

If you run this with any kind of optimization (or even the base level), it will optimize the entire operations away, making it equivalent to `number = 0xFFE0;` .

You need to make the number change at run-time and you need to do the operation a lot of times too, maybe like so:

``````unsigned int and_operator(unsigned int number) {
return number & (~0x1F);
};

unsigned int bit_shifting(unsigned int number) {
return (number >> 5) << 5;
};

int main() {

srand((unsigned int)time(NULL));

for(unsigned int i = 0; i < 1000000; ++i)
unsigned int result = and_operator( rand() );

for(unsigned int i = 0; i < 1000000; ++i)
unsigned int result = bit_shifting( rand() );

return 0;
};``````

Then, you time the loops with whatever method you prefer.

>Then, you time the loops with whatever method you prefer.
Thanks, after testing, the results are almost the same on my pc

ps : I declare inline before those function to eliminate the cost of
calling function

>>But it is always 0 after optimize

What does that tell you? That unless your doing this for a legitimate reason, you shouldn't have to worry about it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.