Reputation: 5659
Given the question:
Write C expressions, in terms of variable x, for the following values. Your code should work for any word size w ≥ 8. For reference, we show the result of evaluating the expressions for x = 0x87654321, with w = 32.
B. All but the least significant byte of x complemented, with the least significant byte left unchanged. [0x789ABC21].
I came up with the solution:
(~x)^0xFF
but the provided solution was: x ^ ~0xFF
- are these equivalent expressions?
Upvotes: 2
Views: 741
Reputation: 144750
Actually, there are not always equivalent, and your solution is far better:
(~x) ^ 0xFF
complements x
for all integer types and restores the low order byte.
x ^ ~0xFF
is more tricky: ~0xFF
will be computed as an int
and then extended to the type of x
before xoring. It may not work as expected if x
is an integer type larger than int
and the representation of int
is sign+magnitude.
Indeed, the following code:
unsigned long x = 12345678;
x = x ^ ~0xFF;
Produces the following warning with clang -Weverything
:
xxo.c:4:13: warning: implicit conversion changes signedness: 'int' to 'unsigned long' [-Wsign-conversion]
x = x ^ ~0xFF;
~ ^~~~~
Furthermore, note that neither expression is correct if the size of w
is smaller than the size of int
. Say for example that int
is 32 bits and short
is 16 bits:
unsigned short x = 0x4321;
The expected result should be 0xBC21
, but:
x ^ ~0xFF -> 0x4321 ^ 0xFFFFFF00 -> 0xFFFFBC21
and
(~x) ^ 0xFF -> 0xFFFFBCEF ^ 0xFF -> 0xFFFFBC21
To fix this issue, the expression should be cast to the type of x
, preferably an unsigned type.
Finally, note that you can shorten the expression this way: 0xFF ^ ~x
Upvotes: 1
Reputation: 424
~
is irrelevant.x
and track down its value:
on our left expression every 1-bit becomes due to negation 0-bit and then 1-bit again after XORing with 0xFF
constant. 0-bit for same reasons becomes 0-bits.
on our right expression we happen to XOR x
with 0 value in each bit. from XOR binary table it is easy to see that each bit in x will remain the same: 1-bits stays the same and 0-bits stays the same. And there you have it, expressions yield the same results.
long road for simple answer...Upvotes: 0
Reputation: 149
Yes.
And you can leave out (). ~ takes precedence over ^ ... and even if it didnt ( like ~(x^0xFF) ) you would still get the same result ...
Ain't that funny ?
Upvotes: 0