zipzit
zipzit

Reputation: 4017

Can anyone explain this Image Resolution Setup code? Exactly what is going on here

I'm trying to understand someone else's code for raw image management.

Here's what I'm looking at:

// Resolution has to be a power of 2. 
// This code finds the lowest RxR resolution which has equal or more pixel than requested
uint32_t higher = std::max(resolutionX, resolutionY);
higher--;
higher |= higher >> 1;
higher |= higher >> 2;
higher |= higher >> 4;
higher |= higher >> 8;
higher |= higher >> 16;
higher++;
internResolution = higher;

I understand that |= is the Bitwise Or operator and that >> is the Shift Bits Right operator. What I'm not getting is why the original code was designed this way. I think this pushes Resolution to be a perfect factor of 2, and I'm assuming that is to maintain Pixel perfect integer ratio logic, but this code seems an odd way to get there.

Can someone explain what is going on here, and perhaps why this is designed this way? Is this just an abstruse way to get to "Smallest power of 2 greater than or equal to n"

Upvotes: 2

Views: 39

Answers (1)

hobbs
hobbs

Reputation: 240414

A number which is one less than a power of two is all 0 bits on the left and all 1 bits on the right (e.g. 1112 = 7, 111111112 = 255).

The sequence of |= operators will make sure that for any set bit in the input, all of the bits to its right will also be set — first, copy each bit right by 1, then copy each pair of bits right by 2, then by 4, etc. The result will be a number that's one less than a power of two, and it never copies any bits to the left, so it will be the next highest number of that form.

So, subtract one, compute the next one-less-than-a-power-of-two, and then add one, and indeed, you're getting the next power of two >= the original input, in an efficient way.

Upvotes: 2

Related Questions