This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Doubts in basic bit wise operators.  RSS feed

 
dinesh Venkatesan
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Consider the following code:
public class Tester {
public static void main(String[] args) {
int c = 2147483647;
int d = ~c;
System.out.println(c);
System.out.println(d);
}
}

The variable c contains the binary equivalent of
1111 1111 1111 1111 1111 1111 1111 1111.
hence, ~c should result in 0000 0000 0000 0000 0000 0000 0000 0000.
But why am i getting the output as
-2147483648.
Please explain.
Thanks in Advance!
dinesh.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by dinesh Venkatesan:
Hi All,

Consider the following code:
public class Tester {
public static void main(String[] args) {
int c = 2147483647;
int d = ~c;
System.out.println(c);
System.out.println(d);
}
}

The variable c contains the binary equivalent of
1111 1111 1111 1111 1111 1111 1111 1111.
hence, ~c should result in 0000 0000 0000 0000 0000 0000 0000 0000.
But why am i getting the output as
-2147483648.
Please explain.
Thanks in Advance!
dinesh.


Remember that the first bit is the sign bit, so the bit representation of c is

0111 1111 1111 1111 1111 1111 1111 1111
 
Kaydell Leavitt
Ranch Hand
Posts: 690
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might consider using the BitSet class if you want bit-vectors that (I don't think) that don't have a sign bit. Also, there is no 32 bit limit, such as ints have, and there isn't even a 64 bit limit, such as longs have.

-- Kaydell
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!