Reputation: 47619
I want to use some integer type as a bit mask. I want to know for which n
it's guaranteed that any number from 0 to 2^n-1
is avaliablle in this type. (Actually I'm going to use uintmax_t
)
I know it's usually 8 * sizeof(uintmax_t)
(or probably CHAR_BIT * sizeof(uintmax_t)
), but I guess it isn't guaranteed.
So I want, to find this n
other way.
How do I achieve this?
Upvotes: 1
Views: 675
Reputation: 13320
Use the cstdint
include.
It provides cross-platform fixed-size typedef
s for integer types and macro constants for its limits.
#include <cstdint>
std::int8_t Signed = 0; // granted to 8bit size.
std::uint8_t Unsigned = 0; // granted to 8bit size.
Signed = INT8_MAX; // store the max value for a signed 8bit value.
Unsigned = UINT8_MAX; // store the max value for an unsigned 8bit value.
Hope it helps.
Upvotes: 2
Reputation: 20027
The answer would be 1+log2((UINTMAX_MAX>>1)+1)
It can also be derived by counting bits with repeated shifting.
Upvotes: 1
Reputation: 227370
There is nothing wrong with using the sizeof
operator in combination with CHAR_BIT
const std::size_t nBits = CHAR_BIT * sizeof(some_integer_type);
This would also work for other built-int types, as well as user defined types.
Upvotes: 4