• Post Reply Bookmark Topic Watch Topic
  • New Topic

Shift operators working on negative numbers  RSS feed

 
sumit bajaj
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Please anyone could help me regarding the working of all 3 shift opearors used on negative numbers.

Thanks in advance.
Sumit
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, but what's your question?
 
sumit bajaj
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually i want this explanatio.

For eg:-- if i have Decimal Number byte b=127. It's Binary is 01111111. i want to shift it left like . b<<1 then surely binary will be 11111110 .ie. it's nEgative number bacuase left most bit is 1. but how the answer came (-2). i didn't get this thing. please help me.
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java the integer is a signed two�s complement integer

The following link will explain that for you

[url=http://en.wikipedia.org/wiki/Two%27s_complement]Two's complement[/url]

So 11111110 = -2.
 
shankar reddy
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
given 127<<1

its binary form 01111111

we need to shift 1 bit field so

it will become 11111110.
because of the MSB is 1 .. the result will be negative number.
in order to get the value from 11111110

use 2's complement.
1's complement. 00000001
add 1 1
---------
00000010
it gives 2.
beacuse of MSB (negative) the result is -2
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by sumit bajaj:
...binary will be 11111110 .ie. it's nEgative number bacuase left most bit is 1. but how the answer came (-2)...

This has nothing to do with shifting of negative numbers -- it's about how signed values are stored in binary format. As described above, you basically get the value by inverting the bits, then adding 1...

11111110 original
00000001 inverting bits
00000010 adding one

This value is 2, so the original value is -2.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!