Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does sizeof(T) * CHAR_BIT guarantee bit size?

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?

like image 776
Trevor Hickey Avatar asked Mar 08 '16 23:03

Trevor Hickey


People also ask

Is sizeof char guaranteed to be 1?

Even if you think of a “character” as a multi-byte thingy, char is not. sizeof(char) is always exactly 1. No exceptions, ever.

Is sizeof in bits or bytes?

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.

Is a char always 8 bits in C?

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).

What is sizeof char * in C?

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.


2 Answers

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.

like image 150
R.. GitHub STOP HELPING ICE Avatar answered Sep 29 '22 07:09

R.. GitHub STOP HELPING ICE


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.

like image 44
chux - Reinstate Monica Avatar answered Sep 29 '22 06:09

chux - Reinstate Monica