让x = (0&0xFFFFFFFF) + ~0 +1 ,x 的值是多少?
我正在研究AC位作业,因为它要求我在不使用'!'的情况下实施逻辑否定的问题之一;这就是我想到的:
`
(0 & 0xFFFFFFFF) // S1: 0s & ones should return 0s right?
+ ~0 +1 // S2: then to the value above I add 1 and the not value of 0 (which in my understanding is 0xFFFFFFFF)
`
现在以人类语言,S1结果:0x0000,s2:0x0000-0 + 1 最终应该返回1。我得到0。我在哪里出错?
预先感谢:)
编辑: 您认为如果修改这种方法有希望吗?并计算一个事实,即我可以通过一个非零的数字,结果给我0。 !(n)= 0,除非n == 0,否则它应该返回1。
I'm working on a c bit homework, for one of the questions it is asking me to implement logical negation without using '!'; this is what I came up with:
`
(0 & 0xFFFFFFFF) // S1: 0s & ones should return 0s right?
+ ~0 +1 // S2: then to the value above I add 1 and the not value of 0 (which in my understanding is 0xFFFFFFFF)
`
Now in human language, S1 result: 0x0000 , S2: 0x0000 - 0 + 1
which should end up returning 1. I instead get 0. Where am I going wrong here??
Thanks in advance :)
edit:
do you think there's hope for this approach if modified? and counting the fact that I can pass a non zero number that should give me a 0 as a result. !(n) = 0 unless n ==0 then it should return 1.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
(0& 0xffffffff)
当然会形成无符号0
或无符号长度0
作为0xfffffffffff
是十六进制的常数, first fits into one of those 2 types. @Eric0
是A 签名0。〜0
翻转所有位 - 结果保留签名。有了非常常见的2补充编码,这是A 签名 -1。然后, 0与
〜0
变为无符号0xffffffff
或0xffff
as -1首先转换为-1一个unsigned
等。取决于int/intemed
的位宽度。将1添加1,值为0。结果为 unsigned 。
添加
〜0
不像减去0
。这需要移动或IFS并经常实现代码或简单地:
soapbox soapbox :IMO,这是一个学习者的分配不佳,因为它鼓励实施依赖于实施代码。 C有一个原因。
(0 & 0xFFFFFFFF)
certainly forms anunsigned 0
orunsigned long 0
as0xFFFFFFFF
is a hexadecimal constant that first fits into one of those 2 types. @Eric0
is a signed 0.~0
flips all the bits - the result remains signed. With the very common 2's complement encoding, this is a signed -1.Then the addition of an unsigned 0 with
~0
becomes unsigned0xFFFFFFFF
or0xFFFF
as -1 is first converted to anunsigned
, etc. depending on the bit width ofint/unsigned
.Adding 1 to that, the value is 0. The result is unsigned.
Adding
~0
is not like subtracting0
.This requires shifts or ifs and often implementation depended code or simply:
Soapbox: IMO, it is a poor assignment for a learner as it encourages implementation dependent code. C has !` for a reason.
〜0
不是-0
,它是-1
。如有必要,请阅读两者的补充编码。所以你的表达方式是:
~0
is not-0
, it's-1
. If necessary, read up on two's complement encoding.So your expression is:
每个操作数具有类型
int
的表达式等同于(如果使用内部表示)
,那又等同
于编译器使用2个整数的补充表示,以产生
> code> 0
。因此,
s1
和s2
均等于0
,因此结果也等于0
。This expression in which each operand has the type
int
is equivalent to (if to use the internal representation)
that in turn is equal to
provided that the compiler uses the 2's complement representation of integers that yields
0
.So
S1
andS2
are both equal to0
and hence the result is also equal to0
.