aspose file tools*
The moose likes Beginning Java and the fly likes why is this giving a positive answer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "why is this giving a positive answer" Watch "why is this giving a positive answer" New topic
Author

why is this giving a positive answer

Vijay Raj
Ranch Hand

Joined: Oct 10, 2005
Posts: 110


Here 0x88 = -120. When we do the bitwise AND, its implicitely converted to an integer and since 0xff = 255, we should get the same number as output. So, the variable i must be equal to -120. Why am I getting a positive result (136).

Are the extra bits simply added(prefixed) without maintaining the negative sign. If that's the case, then the answer is fine. But why is this so.

regards,
vijay.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19060
    
  40

Integers are 32 bits wide, so in order to have an AND operation that does nothing, you need to use 0xffffffff.

In your case, the AND operation will merely keep the lowest 8 bits, which for an integer, does not include the sign bit.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Vijay Raj
Ranch Hand

Joined: Oct 10, 2005
Posts: 110
So, is (byte)0x88 is automatically converted to 0x00000088 while performing the bitwise AND. Then why doesn't

convert 0x88 to 0x00000088. Here, it uses the negative value.

What I want to ask is that while doing bitwise operation, the sign bit is not taken into consideration and zeros are blindly prefixed. But while doing non-bitwise operations such as addition, multiplication etc, the sign bit is not compromised with. Why?

regards,
vijay.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19060
    
  40

So, is (byte)0x88 is automatically converted to 0x00000088 while performing the bitwise AND. Then why doesn't ...


No, that is not what is happening... When a byte is casted to an integer the sign bit is extended out. So, 0x88 as byte should covert to 0xffffff88 as an integer.

The issue is the AND operation... 0xffffff88 & 0x000000ff => 0x00000088

Henry
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why is this giving a positive answer