aspose file tools*
The moose likes Beginning Java and the fly likes confused about the “~” operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "confused about the “~” operator" Watch "confused about the “~” operator" New topic
Author

confused about the “~” operator

Preety Narashimhan
Greenhorn

Joined: Aug 19, 2002
Posts: 28
Was a little bit confused about the “~” operator. Please clarify.
Consider this eg:
3 is represented in the binary form in this manner
00000000 00000000 00000000 00000011
When we say ~3 we invert the “0” bits to “1” right?
So it becomes
11111111 11111111 11111111 11111100
which when converted into decimal becomes :
………+16+8+4+0+0
right? And since the last higher bit is “1” it is a negative number.
Then how is ~3 = -4??? What is the binary format of –4??
I feel
00000000 00000000 00000000 00000100 = 4
10000000 00000000 00000000 00000100 = -4
Is this rite?
Please correct me if I am wrong.
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Nope. Negative numbers are stored in twos compliment form.
00000000 00000000 00000000 00000100 = 4
11111111 11111111 11111111 11111011 = swap all the digits
11111111 11111111 11111111 11111100 = now add 1
And that's how negative numbers are stored.


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
You may want to take a look at this past conversation on the ~ operator. David posted a nice looking link at the end of it.


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Preety Narashimhan
Greenhorn

Joined: Aug 19, 2002
Posts: 28
Hey tx for that "bit" of information worked wonders for me ...
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: confused about the “~” operator