• News

• Industries

• Learning & Support

• Community

• Marketplace

# How can I round a number to the closest power of 2?

As mentioned in the title, I would like to find a series of blueprint nodes that allows me to round a given number to the closest power of two value.
How could I do that?

Thanks

So you want 30 to be 32 and 35 to be 64?

You could make a C++ Blueprint Function Library class and create a static BlueprintCallable function.

MyBlueprintFunctionLibrary.h

``````
public:
UFUNCTION(BlueprintCallable)
static int32 GetRoundUpPowerOfTwo(int32 Value);

``````

MyBlueprintFunctionLibrary.cpp

``````
int32 UMyBlueprintFunctionLibrary::GetRoundUpPowerOfTwo(int32 Value)
{
int32 result = 1;
return result << FGenericPlatformMath::FloorLog2(FMath::Max(Value, 1) * 2);
}

``````

If you instead want to round down then just remove the *** 2** .

I donâ€™t know any easy way of doing this purely in Blueprint.

Yes, thatâ€™s what I am aiming to! I would like the given number to round to the closest power of two so in your example also 35 would round to 32, but if I get 55 it will round to 64 or 140 will round to 128.
Unfortunately, I would need a blueprint way to do it, because I am at zero with my C++ knowledge

You can do it like this:

â€¦ Quick test, so not sure if this is the best solution/errorproof, but it seems to work. You can test it by making these variables public or printing the value.

Thanks for that
Now I just need to understand how to make a blutility out of it