gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:43:27 25 4
gpt4 key购买 nike

考虑以下辅助结构:

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>()
> {};

对于每个整数类型 T这样 std::is_integral<T>::valuetrue除了 bool按照标准,我是否可以保证:

  • 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++ 提案,所以我需要确定这是否符合标准,目前我还不太清楚。

最佳答案

是的,当然有!

[基本类型] 3.9\4

The value representation of an object is the set of bits that hold the value of type T.

[基础.基础] 3.9.1\3

The range of non-negative values of a signed integer type is a subrange of the corresponding unsigned integer type, and the value representation of each corresponding signed/unsigned type shall be the same.

[基础.基础] 3.9.1\7

The representations of integral types shall define values by use of a pure binary numeration system.50

50) A positional representation for integers that uses the binary digits 0 and 1, in which the values represented by successive bits are additive, begin with 1, and are multiplied by successive integral power of 2, except perhaps for the bit with the highest position. (Adapted from the American National Dictionary for Information Processing Systems.)

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

[numeric.limits.members] 18.3.2.4\9

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

如果他们暗示,符号位必须在所谓的sign-and-magnitude representation中。 ,那么您会将这些表达式计算为 true :

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

对于以二进制或二进制补码表示的有符号整数类型 T。 所以,我会放一个 static_assert不管怎样,你知道...

关于c++ - 根据标准,整数中的值表示位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34611181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com