The number of bits representing the value in integer, according to the standard?

Consider the following auxiliary structures:

template <class T> struct bit_count_1: std::integral_constant< std::size_t, std::numeric_limits<typename std::make_unsigned<T>::type>::digits > {}; template <class T> struct bit_count_2: std::integral_constant< std::size_t, std::numeric_limits<T>::digits + std::is_signed<T>::value > {}; template <class T> constexpr std::size_t compute_bit_count() { using type = typename std::make_unsigned<T>::type; constexpr type zero = 0; constexpr type one = 1; constexpr type max = ~zero; type current = max; std::size_t i = 0; while (current) { current >>= one; ++i; } return i; } template <class T> struct bit_count_3: std::integral_constant< std::size_t, compute_bit_count<T>() > {}; 

For each integral type T such that std::is_integral<T>::value is true except for bool , I have a guarantee, by standard, that:

  • bit_count_1 , bit_count_2 and bit_count_3 have the same value N
  • T x = 1; x <<= (N - 1) T x = 1; x <<= (N - 1) clearly defined
  • T x = ~static_cast<T>(0); x >>= (N - 1) T x = ~static_cast<T>(0); x >>= (N - 1) is clearly defined

I am currently working on a proposal in C ++, so I need to be sure if this is true according to the standard or not, and at the moment this is a bit unclear to me.

+5
source share
1 answer

Yes of course you have!

[basic.types] 3.9 \ 4

A representation of an object value is a collection of bits that hold a value of type T.

[basic.fundamental] 3.9.1 \ 3

The range of non-negative values ​​of the signed integer type is equal to the sub-range of the corresponding unsigned integer type and the value of the representation of each corresponding signed / unsigned type must be the same .

[basic.fundamental] 3.9.1 \ 7

Representations of integral types must define values ​​using a pure binary numbering system. 50

50) A positional representation for integers that uses the binary digits 0 and 1, in which the values ​​represented by consecutive bits are additive, start with 1 and multiply by consecutive integral power 2 , with the possible exception of the bit with the highest position . (Adapted from the American National Dictionary for Information Processing Systems.)

But it depends on what are not signed bits:

[numeric.limits.members] 18.3.2.4 \ 9

For integer types, the number of non-sign bits in the view.

If they imply that the sign bit should only be in the so-called sign and size value , then you would get these expressions as true :

  • bit_count_2<T>{} > bit_count_1<T>{} and
  • bit_count_2<T>{} > bit_count_3<T>{} ,

for a signed integer type T, represented in two or one complement. So, I would put static_assert , you know ...

+2
source

Source: https://habr.com/ru/post/1239882/


All Articles