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.
CodePudding user response:
(0 & 0xFFFFFFFF)
certainly forms an unsigned 0
or unsigned long 0
as 0xFFFFFFFF
is a hexadecimal constant that first fits into one of those 2 types. @Eric
0
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 unsigned 0xFFFFFFFF
or 0xFFFF
as -1 is first converted to an unsigned
, etc. depending on the bit width of int/unsigned
.
Adding 1 to that, the value is 0. The result is unsigned.
Where am I going wrong here?
Adding ~0
is not like subtracting 0
.
implement logical negation without using '!';
This requires shifts or ifs and often implementation depended code or simply:
y = x == 0;
Soapbox: IMO, it is a poor assignment for a learner as it encourages implementation dependent code. C has !` for a reason.
CodePudding user response:
Now in human language, S1 result: 0x0000 , S2: 0x0000 - 0 1
~0
is not -0
, it's -1
. If necessary, read up on two's complement encoding.
So your expression is:
(0 & 0xFFFFFFFF) ~0 1 =
(0 & whatever) ~0 1 =
0 ~0 1 =
~0 1 =
-1 1 =
0
CodePudding user response:
This expression in which each operand has the type int
~0 1
is equivalent to (if to use the internal representation)
0xFFFFFFFF 1
that in turn is equal to
-1 1
provided that the compiler uses the 2's complement representation of integers that yields 0
.
So S1
and S2
are both equal to 0
and hence the result is also equal to 0
.