In reply to cy_skyworld:
The problem with the code shown is you are using the bitwise not (~) instead of the logical not(!).
It always helps to show a complete runnable example. I can only guess in your second attempt that you used a different operator.