【发布时间】:2018-08-21 19:58:44
【问题描述】:
以下代码只要求输入一个数字num,然后输入该数字的一点tbit 来切换/反转,然后打印新数字ans。
在 debian 9 上使用带有 gcc 编译器版本 6.3.0 20170516 的 Geany,当我执行以下代码时,我得到的答案 ans 为 6,当我预计编译器或运行时错误告诉我我退出时界限之类的。
使用这个版本的 gcc,sizeof(int) 返回四个字节或 32 位。当我尝试切换第 100 位时,ans=6 发生了什么?
示例输入:
Enter a number : 22
Enter the bit you want to toggle : 100
输出:
The number you entered is 22
after toggling the 100 bit
the new number is 6.`
代码:
#include <stdio.h>
int main ()
{
int num, tbit, tool = 1, ans;
printf(Enter a number :");
scanf("%d", &num);
printf(Enter the bit you want to toggle :");
scanf("%d", &tbit);
ans = (tool<<tbit) ^ num;
printf("The number you entered is %d after toggling the %d bit the new
number is %d\n" , num, tbit, ans);
return 0;
}
【问题讨论】:
-
为什么要切换没有 100 位的数据类型的第 100 位?这听起来有问题。
-
@cleblanc:我猜 OP 只是在重新输入代码时出错,因为输出似乎表明
scanf是正确的。 -
@ChristianGibbons 只是好奇会发生什么。
-
你不应该依赖这样奇怪的实验。 C 中有许多未定义行为的示例,因此虽然您的实验可能会显示一个结果,但另一个系统或另一个运行可能会产生另一个结果。如果您有兴趣了解更多有关事物如何工作的信息,我建议您花些时间看一下 C 标准。 open-std.org/jtc1/sc22/wg14/www/standards
-
“OP”是原始帖子或原始海报,具体取决于上下文......他在谈论你。 webopedia.com/TERM/O/op_original_poster.html
标签: c gcc int bit-manipulation toggle