2

I have a sample problem with w=1, y=7, z=0, x = ~(w && y) | y; and the solution is x = -1, but I can't figure out why?

Here is my thought process:
(w && y) = (1 && 7) = 1
~1
1 in bits is 0000 0001
~1 in bits is 1111 1110

Not sure what to do from here.

raphnguyen
  • 3,565
  • 18
  • 56
  • 74

4 Answers4

6

The last step is a bitwise OR so you get:

1111 1110 | 0000 0111 = 1111 1111

which is -1.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
1

~1 in bits is 1111 1110, 1111 1110 or 0000 0111 is 1111 1111, and 1111 1111 is -1. The most significant bit is the negative flag, and negative numbers are subtractive, I guess you could say. That's why a signed byte can hold down to -128 but only up to 127.

Ry-
  • 218,210
  • 55
  • 464
  • 476
0

You're right that ~(w && y) gives 1111...0. The last bit of 7 is 1, so |ing this with 7 gives 1111...1, or -1.

Daniel Lubarov
  • 7,796
  • 1
  • 37
  • 56
0

First, you should be using & instead of && for bitwise operations. Second, after ~1 = 111...1110 is calculated, it is ORed with y (7) to get 1111..1111, the 2's-complement representation of -1.

jwodder
  • 54,758
  • 12
  • 108
  • 124
  • 1
    I would not suggest that, as you do not know the intention of the code (at least I don't know what it really does) and the results of & and && are different. – Christian Rau May 09 '11 at 01:01