• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How does this work

 
sun par
Ranch Hand
Posts: 257
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The Ouptput is 5. Can someone explain
Thanks
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
byte b1 = -5;
int i = 0xff;
byte b2 = (byte) (b1 ^ 1);
f 1011
f 1111
_______^
0 0100
b2++;
4 + 1
^ is or-exclusive. Only yields true if its two entries are distinct. That is 1^1 or 0^0 yield 0, but 1^0 or 0^1 yields 1
Read Cat and Mouse Games with bits for more.
 
Todd Killingsworth
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jose, where did this come from? Operand was 1, not -1.
f 1011
f 1111 <---- ???
_______^
0 0100
I'm getting an answer of -5.

Taking this from the top:

f 1011 -5
f 0001 1
_______^
0 1010 -6
f 0001 1
_______+
0 1011 -5

Please let me know if I'm missing something - my 2's compliment isn't very sturdy yet
Todd Killingsworth
 
sun par
Ranch Hand
Posts: 257
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I also get -5 and I am confused
 
John Paverd
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by sun par:
I also get -5 and I am confused

Sunita
If you replace byte b2 = (byte) (b1 ^ 1);
with byte b2 = (byte) (b1 ^ i);
the result will be 5. Perhaps there was a typo in the test question?
[ January 10, 2003: Message edited by: John Paverd ]
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with John, not only do you get 5, but you actually use i - which otherwise you don't use.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic