• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why is this giving a positive answer

 
Vijay Raj
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Marshal
Pie
Posts: 21190
80
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21190
80
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic