6

CHAR_BIT defines the number of bits per character. But it is an old macro. Similar macros have been replaced in recent C++ standards.

Is there a more modern replacement for CHAR_BIT in C++11/14/17?

Silicomancer
  • 8,604
  • 10
  • 63
  • 130
  • I don't think `std::numeric_limits::digits()` is better than `CHAR_BIT`. – DeiDei Jun 24 '17 at 22:07
  • 5
    I don't understand the motivation of this question. If everything that's old must be replaced, we'd never have anything stable. Why do you think it's necessary to replace `CHAR_BIT`, and what's wrong with it? – Kerrek SB Jun 24 '17 at 22:08
  • 8
    Wow. Keep calm. Where did I say anything about my motivation? Where did I say CHAR_BIT is wrong? Or a replacement would be *necessary*? I think templated code can have advantages but I was mainly just curious. – Silicomancer Jun 24 '17 at 22:11
  • 5
    @DeiDei : Perhaps not, but `std::numeric_limits::digits` for example is perhaps better than `sizeof(unsigned long) * CHAR_BIT`, so it is at least consistent if you choose to use it for the larger types too. Note too that `digits` is a data-member, not a member-function. – Clifford Jun 24 '17 at 22:37
  • One has to use `std::numeric_limits::type>::digits` within templates accepting signed types. A bit verbose, I must say. – Emile Cormier May 07 '21 at 00:49

1 Answers1

14

The number of non-sign bits is provided by std::numeric_limits<T>::digits, so it can be determined by:

std::numeric_limits<unsigned char>::digits

Note the use of the unsigned qualifier to ensure there are no sign bits.

Clifford
  • 88,407
  • 13
  • 85
  • 165
  • One has to use `std::numeric_limits::type>::digits` within templates accepting signed types. A bit verbose compared to `CHAR_BIT * sizeof(T)`, I must say. – Emile Cormier May 07 '21 at 00:49
  • 1
    @EmileCormier why would you do that though? a signed type has the same number of bits as it's unsigned counterpart, so I am suggesting you use the unsigned qualifier regardless of the type of the other operands involved in an expression. If your point needs elaboration to explain why this is useful, post an answer. – Clifford May 07 '21 at 06:34
  • You can't apply the `unsigned` qualifier to types such as `int64_t`. https://stackoverflow.com/questions/44626223/why-unsigned-int64-t-gives-an-error-in-c – Emile Cormier May 07 '21 at 21:18
  • Oh, I think I misinterpreted your answer. You're proposing `std::numeric_limits::digits * sizeof(T)` instead of `CHAR_BIT * sizeof(T)`. My bad. – Emile Cormier May 07 '21 at 21:22
  • @EmileCormier Indeed - I answered the question ;-) – Clifford May 07 '21 at 21:28
  • Yep, brainfart. I was doing a lot of `CHAR_BIT * sizeof(T)` in my code and that was still stuck in my brain when I read your answer. – Emile Cormier May 07 '21 at 21:29