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

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

问题描述

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

  //例
INT美孚(INT A,INT B,INT随身携带,诠释REM){
  int2x℃; //有些类型的两倍宽在`int`
  C =(int2x)A * B +随身携带;
  回报(INT)(C%REM);
}

考虑(这似乎限制的sizeof()有用性)和非2`s补充整数(这限制位点播),用于填充的潜力,...


  

执行以下操作总是创建所需要的类型?结果
  如果不是,怎么code。至少一个合理的解决方案,即使不是完全的便携式?



 的#include<&limits.h中GT;
#包括LT&;&stdint.h GT;#如果LONG_MAX / 2 / INT_MAX - 2 == INT_MAX
  长期的typedef int2x;
  typedef的无符号长unsigned2x;
#elif指令LLONG_MAX / 2 / INT_MAX - 2 == INT_MAX
  typedef的长长int2x;
  typedef的无符号长长unsigned2x;
#elif指令INTMAX_MAX / 2 / INT_MAX - 2 == INT_MAX
  的typedef intmax_t型int2x;
  的typedef uintmax_t型unsigned2x;
#其他
  #ERROR int2x / unsigned2x不可用
#万一


结果
资格:总是,如果长长还会将intmax_t ,不工作是确定 #ERROR 。结果
我想知道的是,如果长长还会将intmax_t至少有1 将工作,将 int2x 正确键入?

注:以上数据假设 xxx_MAX 有一些奇怪的权力,以2减1。也许一个好的假设?在至少2平台上的作品,但是这是一个很难的可移植性很大考验。


解决方案

假设所有* _MAX常量的形式(2 ^ N)-1 是有效的。见的 6.2.6重新$ P $类型psentations 的,特别的 6.2.6.2整数类型的,其中无符号整数类型的重新presentations和正值符号整数类型充分定义为纯二进制,从而产生一个最大比二的幂少一个。

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

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


[Edit]
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?

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.

解决方案

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天全站免登陆