Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get number of bits in char

Tags:

c++

How do I get the number of bits in type char?

I know about CHAR_BIT from climits. This is described as »The macro yields the maximum value for the number of bits used to represent an object of type char.« at Dikumware's C Reference. I understand that means the number of bits in a char, doesn't it?

Can I get the same result with std::numeric_limits somehow? std::numeric_limits<char>::digits returns 7 correctly but unfortunately, because this value respects the signedness of the 8-bit char here…

like image 829
mkluwe Avatar asked Feb 11 '10 19:02

mkluwe


People also ask

How many bits are a char in C?

In practice, char is usually 8 bits in size and short is usually 16 bits in size (as are their unsigned counterparts).

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


3 Answers

CHAR_BIT is, by definition, number of bits in the object representation of type [signed/unsigned] char.

numeric_limits<>::digits is the number of non-sign bits in the value representation of the given type.

Which one do you need?

If you are looking for number of bits in the object representation, then the correct approach is to take the sizeof of the type and multiply it by CHAR_BIT (of course, there's no point in multiplying by sizeof in specific case of char types, since their size is always 1, and since CHAR_BIT by definition alredy contains what you need).

If you are talking about value representation then numeric_limits<> is the way to go.

For unsigned char type the bit-size of object representation (CHAR_BIT) is guaranteed to be the same as bit-size of value representation, so you can use numeric_limits<unsigned char>::digits and CHAR_BIT interchangeably, but this might be questionable from the conceptual point of view.

like image 172
AnT Avatar answered Sep 20 '22 13:09

AnT


If you want to be overly specific, you can do this:

sizeof(char) * CHAR_BIT

If you know you are definitely going to do the sizeof char, it's a bit overkill as sizeof(char) is guaranteed to be 1.

But if you move to a different type such as wchar_t, that will be important.

like image 41
R Samuel Klatchko Avatar answered Sep 18 '22 13:09

R Samuel Klatchko


Looking at the snippets archive for this code here, here's an adapted version, I do not claim this code:

int countbits(char ch){
    int n = 0;
    if (ch){
        do n++;
        while (0 != (ch = ch&(ch-1)));
    }
    return n;
}

Hope this helps, Best regards, Tom.

like image 25
t0mm13b Avatar answered Sep 18 '22 13:09

t0mm13b