如何确定宽度是“int"和“unsigned"两倍的整数类型? [英] How to determine integer types that are twice the width as `int` and `unsigned`?

查看:14
本文介绍了如何确定宽度是“int"和“unsigned"两倍的整数类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

中间乘法的值通常需要两倍的位数作为输入.

Values of intermediate multiplication typically need twice the number of bits as inputs.

 // Example
int foo(int a, int b, int carry, int rem) {
  int2x c;  // Some type that is twice as wide at `int`
  c = (int2x)a * b + carry;
  return (int) (c % rem);
}

考虑到填充的可能性(这似乎会限制 sizeof() 的有用性)和非 2 的补码整数(这会限制位 dibbling),...

Considering the potential for padding, (which appears to limit sizeof() usefulness) and non-2`s complement integers (which limits bit dibbling), ...

以下是否总是创建所需的类型?
如果不是,如何编写至少一个合理的解决方案,即使不是完全可移植的?

Does the following always create the needed type?
If not, how to code at least a reasonable solution, even if not entirely portable?

<小时>

#include <limits.h>
#include <stdint.h>

#if LONG_MAX/2/INT_MAX - 2 == INT_MAX
  typedef long int2x;
  typedef unsigned long unsigned2x;
#elif LLONG_MAX/2/INT_MAX - 2 == INT_MAX
  typedef long long int2x;
  typedef unsigned long long unsigned2x;
#elif INTMAX_MAX/2/INT_MAX - 2 == INT_MAX
  typedef intmax_t int2x;
  typedef uintmax_t unsigned2x;
#else
  #error int2x/unsigned2x not available
#endif

<小时>


qualify:"always",如果longlong longintmax_t,不工作#error.
我想知道的是 longlong longintmax_t 中的至少 1 个是否可以工作,int2x 输入正确吗?



Qualify:"always", if long, long long and intmax_t, do not work it is OK to #error.
What I want to know is if at least 1 of long, long long, or intmax_t will work, will int2x be correctly typed?

注意:以上假设 xxx_MAX 是 2 次幂减 1 的一些奇数.也许是一个好的假设?以上至少在 2 个平台上工作,但这并不是一个很好的可移植性测试.

Notes: The above assumes xxx_MAX are some odd power-of-2 minus 1. Maybe a good assumption? The above works on at least 2 platforms, but that is hardly a great portability test.

推荐答案

假设所有 *_MAX 常量的形式为 (2^n)-1 是有效的.请参阅6.2.6 类型的表示,尤其是6.2.6.2 整数类型,其中无符号整数类型的表示和有符号整数类型的正值完全定义为纯二进制,因此产生的最大值小于 2 的幂.

The assumption that all *_MAX constants are of the form (2^n)-1 is valid. See 6.2.6 Representations of Types, and particularly 6.2.6.2 Integer types, where the representations of unsigned integer types and the positive values of signed integer types are fully defined as pure binary, thus yielding a maximum which is one less than a power of two.

这篇关于如何确定宽度是“int"和“unsigned"两倍的整数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆