根据标准,整数中的值表示位数?

Vin*_*ent 5 c++ standards bit language-lawyer c++14

考虑以下帮助器结构:

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>()
> {};
Run Code Online (Sandbox Code Playgroud)

对于每一个整数类型T,从而std::is_integral<T>::valuetruebool我必须保证,在标准,即:

  • bit_count_1,bit_count_2bit_count_3具有相同的价值N
  • T x = 1; x <<= (N - 1) 很明确
  • T x = ~static_cast<T>(0); x >>= (N - 1) 很明确

我目前正在制定一个C++提案,所以我需要确定这是否符合标准,或者不是,目前对我来说有点不清楚.

Eug*_*sky 2

是的,当然,你(在某种程度上)有!

[基本类型] 3.9\4

对象的值表示是保存类型T 的值的一组位。

[基础.基础] 3.9.1\3

有符号整数类型的非负值范围是相应无符号整数类型的子范围,并且每个相应的有符号/无符号类型的表示 应相同

[基础.基础] 3.9.1\7

整数类型的表示应使用纯二进制计数系统来定义值。50

50)使用二进制数字 0 和 1 的整数位置表示,其中连续位表示的值是相加的,从 1 开始,并乘以连续的 2 的整数幂,最高位置的位除外。(改编自美国国家信息处理系统词典。)

但这取决于什么是非符号位:

[数字.限制.成员] 18.3.2.4\9

对于整数类型,表示形式中非符号位的数量。

如果他们暗示,符号位必须仅存在于所谓的符号和幅度表示形式中,那么您将把这些表达式计算为true

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

对于以二进制或二进制补码表示的有符号整数类型 T。

但是由于[intro.refs]以及编程语言C标准6.2.6.2\2中指定的类型表示:

对于有符号整数类型,对象表示的位应分为三组:值位、填充位和符号位...

,看起来符号位也以二进制和补码表示形式出现!