Results 1 to 5 of 5
- 10-16-2009, 07:23 PM #1
Confusing with bitwise NOT operator
Hi!
I don't know whether anyone pay attention with bitwise logical NOT operator, but I am confusing with this.
For example, I want to use NOT operator with an integer variable which has value 1, this means (let me take 8 bits instead of 4 bytes) :
andJava Code:1 is 0000 0001
If we run a program for this problem, we get -2 which is not equal to 1111 1110 at allJava Code:~1 is 1111 1110
The thing that I know is that after 1 is converted to 1's complement, the result is converted back to 2's complement and keep the MSB bit unchanged as the sign bit, that's how we get -2. But why is it like that? Does this have any thing related to performance purpose or it's the rule of representing binary number in form of machine code? :(
Thanks and pardon my ignorance about the very basic thing!Write a program to achieve anything you want in your life!
- 10-16-2009, 07:36 PM #2
Senior Member
- Join Date
- Aug 2009
- Posts
- 2,388
- Rep Power
- 6
The advantages of twos complement can found on wikipedia.
- 10-16-2009, 09:03 PM #3
so it's all about the sake of performance.
Thanks for the useful topic on Wiki!Last edited by Willi; 10-16-2009 at 09:06 PM.
Write a program to achieve anything you want in your life!
- 10-16-2009, 09:06 PM #4
Senior Member
- Join Date
- Aug 2009
- Posts
- 2,388
- Rep Power
- 6
Not all about performance. That wiki example mentions other advantages.
- 10-16-2009, 11:06 PM #5
It's because the number is a signed number. So the leading 1 says the number is negative.
1111 1111 = -1
1111 1110 = -2
1111 1101 = -3
...
If the number were unsigned (not supported in Java), then 1111 1110 would equal 254.
I've only used the bitwise not operation when working with bitmasks to clear a specific flag. For example "bitmask & ~flag" will clear the specific flag in the bitmask.CodesAway - codesaway.info
writing tools that make writing code a little easier
Similar Threads
-
Bitwise operations with long
By NewJavaBean in forum New To JavaReplies: 2Last Post: 04-07-2009, 07:37 PM -
Simple code, but confusing
By t.prasanna in forum New To JavaReplies: 5Last Post: 01-22-2009, 10:26 AM -
Confusing IndexOutOfBounds Error?
By tibbyuk in forum New To JavaReplies: 2Last Post: 08-08-2008, 11:42 PM -
Confusing with Frameworks
By hisouka in forum New To JavaReplies: 0Last Post: 08-05-2008, 05:52 AM -
Using the bitwise operators
By Java Tip in forum java.langReplies: 0Last Post: 04-17-2008, 07:39 PM


LinkBack URL
About LinkBacks


Bookmarks