由32位执行左移时,意外的输出 [英] Unexpected output when executing left-shift by 32 bits

查看:138
本文介绍了由32位执行左移时,意外的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我做了十六进制的左移,我得到-1为具有以下code输出:

When I do a left shift of a hex I get -1 as output with the following code:

unsigned int i,j=0;
i= (0xffffffff  << (32-j));
printf("%d",i);

同样,当我改变了移值到32时,输出为0,但我从编译器警告为(左移计数&GT;类型=宽度)

unsigned int i,j=32;
i= (0xffffffff  << (32));
printf("%d",i);

我期待在这两种情况下相同的结果(即0),但得到了困惑为什么显示的情况下,#1的输出错误,并且在情况#2的结果是正确的,但编译器警告!

I was expecting the same results in both the cases (ie, 0), but got confused why is displaying wrong output in case #1, and in case #2 the result is correct but the compiler warns!

结果是32位和64位的x86机器一样的。

The result is same in 32 and 64 bit x86 machines.

有人可以解释上述结果?

Can someone explain the results above?

推荐答案

这是不确定的行为,以左狗屎 32 或更高的32位整数。这是错误的是什么。

It's undefined behavior to left-shit 32 or greater on a 32-bit integer. That's what the error is about.

整数促销活动在每个操作数执行。的结果的类型是
  该促进左操作数。如果右操作数的值是负数或大于或等于促进左操作数的宽度大,其行为是不确定的。

C11 6.5.7 Bitwise shift operators

The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

这篇关于由32位执行左移时,意外的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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