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:

# Shift operators working on negative numbers

sumit bajaj
Greenhorn
Posts: 10
Hi,

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

Sumit

marc weber
Sheriff
Posts: 11343

sumit bajaj
Greenhorn
Posts: 10
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
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
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
---------
00000010
it gives 2.
beacuse of MSB (negative) the result is -2

marc weber
Sheriff
Posts: 11343
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