Skip to content

Instantly share code, notes, and snippets.

@JonasReich
Last active December 19, 2019 17:00
Show Gist options
  • Save JonasReich/7fc5fc8f6b0a33e0affafa0277a9d271 to your computer and use it in GitHub Desktop.
Save JonasReich/7fc5fc8f6b0a33e0affafa0277a9d271 to your computer and use it in GitHub Desktop.
// Copyright 2019, Jonas Reich. All Rights Reserved.
// This file was created for an Unreal Engine project. Feel free to change uint32 to a custom unsigned integer type.
#include "CoreMinimal.h"
#pragma once
/**
* Get the number of bits required to display a given number.
* #TODO: Should be extended with static asserts to ensure it only compiles with unsigned integer types
* or modified to also work with signed ints.
*/
template<typename T>
constexpr uint32 GetMinBitSize(T value)
{
static_assert(sizeof(T) < sizeof(uint32), "GetMinBitSize can only be used with types smaller or equal to uint32");
uint32 Size = 0;
uint32 ValueAsInt = static_cast<uint32>(value);
// continue unsetting bits until ValueAsInt is 0
while (ValueAsInt)
{
// unset Size'th bit
ValueAsInt &= ~(1 << Size);
Size += 1;
}
return Size;
}
static_assert(GetMinBitSize(5) == 3, "GetMinSize(5) returns wrong value! (should be 3)");
static_assert(GetMinBitSize(0) == 1, "GetMinSize(0) returns wrong value! (should be 1)");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment