Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C中检测机器是否为32位_C_Int - Fatal编程技术网

如何在C中检测机器是否为32位

如何在C中检测机器是否为32位,c,int,C,Int,所以我在复习考试,我陷入了这个问题: 2.67◆◆ 您的任务是编写一个过程int_size_is_32(),该过程产生1 当在int为32位的机器上运行时,否则产生0。你是 不允许使用sizeof运算符。这是第一次尝试: 1 /* The following code does not run properly on some machines */ 2 int bad_int_size_is_32() { 3 /* Set most significant bit (msb) of 32-b

所以我在复习考试,我陷入了这个问题:


2.67◆◆ 您的任务是编写一个过程int_size_is_32(),该过程产生1 当在int为32位的机器上运行时,否则产生0。你是 不允许使用sizeof运算符。这是第一次尝试:

1 /* The following code does not run properly on some machines */
2 int bad_int_size_is_32() {
3 /* Set most significant bit (msb) of 32-bit machine */
4 int set_msb = 1 << 31;
5 /* Shift past msb of 32-bit word */
6 int beyond_msb = 1 << 32;
7
8 /* set_msb is nonzero when word size >= 32
9 beyond_msb is zero when word size <= 32 */
10 return set_msb && !beyond_msb;
11 }
1/*以下代码在某些计算机上无法正常运行*/
2 int bad_int size_为_32(){
3/*设置32位计算机的最高有效位(msb)*/
4 int set_msb=1
答:当我们在第4行移位31时,我们溢出,根据无符号整数标准,我们可以表示的最大无符号整数是2^31-1

错误出现在第6行,而不是第4行。编译器消息准确地解释了原因:移位的位数大于类型的大小是未定义的行为


B:在第4行1中,绝对没有办法在运行时测试C中有符号类型的大小。这是因为溢出是未定义的行为;您无法判断是否发生了溢出。如果使用
unsigned int
,您只需计算在结果变为零之前可以将从1开始的值加倍的类型数

如果您希望在编译时而不是运行时执行测试,这将起作用:

struct { int x:N; };

其中,
N
被依次较大的值替换。只要
N
不大于
int
的宽度,编译器就需要接受该程序,当
N
较大时,编译器会以诊断/错误的方式拒绝该程序。

首先,移位30不会产生任何溢出,因为可以移位的最大值是w作战需求文件尺寸为w-1。 所以当w=32时,你可以换到31

当您将其移位32位时会发生溢出,因为lsb现在将移动到超出限制的第33位

所以问题出在第6行而不是第4行

为了B

0xffffffff + 1

如果是32位,则结果为0,否则会出现一些nozero编号。

通过分解左移位,您应该能够遵守C标准

B-

将第6行替换为

int beyond_msb = (1 << 31) << 1;
int beyond_msb = ((1 << 15) << 15) << 2;

int beyond_msb=(1也许你可以从这个问题中找到另一个选择这是一个来自“CS:APP”一书的好问题。第2章中的内容将很好地为您服务。这是编译时的事情。编译器、编译器设置和编译器运行的机器将决定int的大小,而不是程序运行的机器。如果您说错误在第6行而不是第4行,那么B部分如何导致错误不出现?以及ame适用于C部分
int beyond_msb = ((1 << 15) << 15) << 2;
int int_size_is_32() {
//initialise our test integer variable.
int x = 1;  
//count for checking purposes
int count = 0;
//keep shifting left 1 bit until we have got pushed the 1-bit off the left of the value type space.
while ( x != 0 ) {
    x << 1   //shift left
    count++;  
}

return (count==31);
}