Tomilla / CS-APP2e

Homework Problem Solution for <Computer Systems - A Programmer's Perspective. 2nd. ed>
http://csapp.cs.cmu.edu/
MIT License
37 stars 15 forks source link

!x fails when x == 0x...FE. Only !!~x works for all three cases of x. #5

Open ghost opened 6 years ago

ghost commented 6 years ago

https://github.com/Tomilla/CS-APP2e/blob/1e698b8accb693cf0188b43bf534dd828654e8fc/Solution/Chapter%202/S2HP_2.61.c#L32

ghost commented 6 years ago

Three cases of 'x' are: 0xFF: all bits are one -> False 0x00: all bits are zero -> True 0xFE: one bit is zero, but 0xFE evaluates to true, which negated by ! results in False.

In the last case you must have the ones' complement operation. Any number that has at least one zero when negated will always evaluate to True in a logical test. Therefore, !!~x is the only solution which excludes comparison operations.