24小时热门版块排行榜    

查看: 1280  |  回复: 7
当前只显示满足指定条件的回帖,点击这里查看本话题的所有回帖

我爱小虫子

新虫 (正式写手)

[求助] C++一道题目,疑惑 已有2人参与

题目如下图,另外附上书上的解释,没有明白,为什么unsigned char 明明是1个字节,为什么要给他分配16的空间啊,
另外,附上一个连接,我从网上找的,但是也没有明白,这个连接的帖子里是分配了32位。不要小看 b=~a>>4 - ybdesire的专栏 - 博客频道 - CSDN.NET
http://blog.csdn.net/ybdesire/article/details/6583724
我再VC6上也试了题目上的问题,结果是250,和在VS上结果一样的,(因为b只能存放低8位)
再说一下我的疑惑哈,
(1)unsigned char 为什么不是分配了一个字节,
(2)如果不是一个,那应该是16还是32啊(还是视编译器而定啊)
.感谢!!!!

C++一道题目,疑惑
QQ图片20140323170345.jpg


C++一道题目,疑惑-1
QQ图片20140323170430.jpg
回复此楼

» 猜你喜欢

» 本主题相关价值贴推荐,对您同样有帮助:

已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

rbs

木虫 (小有名气)

【答案】应助回帖

★ ★ ★ ★ ★ ★ ★ ★ ★ ★
感谢参与,应助指数 +1
我爱小虫子: 金币+10, ★★★★★最佳答案, 非常感谢,你说的这些确实是我的疑惑,是我对一些概念的模糊,这次一定搞清楚。。 2014-03-25 08:06:26
C标准里面有明确的说明:
Each of the operands shall have integer type.The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand.
移位运算的操作数必须是整型(关于整型还有些说头,但可以确定的是绝对不再是char)。如果操作数不是整型,则会做integer promotion操作,基本上就是转型操作。
另外,对于按位非操作,操作数一样要首先做integer promotion操作。
If an int can represent all values of the original type, the value is converted to an int;
otherwise, it is converted to an unsigned int. These are called the integer promotions。
在这种情况下,a必然会被转为int,然后再按位非。然后再右移5位。在此例中也就是一个负数右移5位。实际上这个答案是不确定的。因为C标准说:
The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type
or if E1 has a signed type and a nonnegative value, the value of the result is the integral
part of the quotient of E1 / 2^E2 . If E1 has a signed type and a negative value, the
resulting value is implementation-defined.
最后一句说明负数的右移是由实现平台自定的,C标准不管。不过一般而言,大家都是会补符号位也就是-1,基本没有补0的。但C标准允许这种可能性。
所以a的值首先是个unsigned char,位非操作前转为int,位非变为负数,右移5位时右边一直补1,最后赋值给b的时候,再进行一个强制转型操作。
2楼2014-03-24 23:43:00
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

rbs

木虫 (小有名气)

【答案】应助回帖

引用回帖:
2楼: Originally posted by rbs at 2014-03-24 23:43:00
C标准里面有明确的说明:
Each of the operands shall have integer type.The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand.
移位运 ...

上述的英文来源于
International Standard Programming languages C, ISO/IEC 9899, second edition
也就是C99标准。
3楼2014-03-24 23:45:23
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖
相关版块跳转 我要订阅楼主 我爱小虫子 的主题更新
信息提示
请填处理意见