programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# why is this giving a positive answer

Vijay Raj
Ranch Hand
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
Posts: 23295
125
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

Vijay Raj
Ranch Hand
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
Posts: 23295
125
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

 Don't get me started about those stupid light bulbs.