There doesn't appear to be any library function for calculating the size of a type in bits.
Am I right to assume that this can be done in the following way?
#include <climits>
template <typename T>
size_t Size_In_Bits(){
return sizeof(T) * CHAR_BIT;
}
Will this always give back the amount of bits that can be targeted on a type?
Even if you think of a “character” as a multi-byte thingy, char is not. sizeof(char) is always exactly 1. No exceptions, ever.
The sizeof operator returns the number of bytes occupied by a variable of a given type. The argument to the sizeof operator must be the name of an unmanaged type or a type parameter that is constrained to be an unmanaged type.
that a char is represented by a byte, that a byte can always be counted upon to have 8 bits, that sizeof (char) is always 1 , and that the maximum theoretical amount of memory I can allocate (counted in char s) is the number of bytes of RAM (+ swap space).
sizeof is a unary operator in the programming languages C and C++. It generates the storage size of an expression or a data type, measured in the number of char-sized units. Consequently, the construct sizeof (char) is guaranteed to be 1.
This is guaranteed to give you size (storage) in bits, but not the width (number of value bits). The latter could be less if the type has padding bits. For unsigned types there you can measure the number of value bits directly by converting -1 to the type (to get the max possible value in the type) and counting them. For signed types, std::numeric_limits<T>::max()
can be used to get the max. Or, if you know the specific type already, you can use the xxx_MAX
macros from limits.h
or stdint.h
.
sizeof(T) * CHAR_BIT
returns the numbers of bits the type takes up in memory.
Yet the size of bits may be more than the bits the integer can be mathematically used - (consider padding bits).
Detail: integers have value bits, sign bit (signed integers) and possible padding bits. All these bits contribute to the storage size.
unsigned char
will never have padding bits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With