File APIs for Java Developers Manipulate DOC, XLS, PPT, PDF and many others from your application. http://aspose.com/file-tools
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of Java Interview Guide this week in the Jobs Discussion forum!

# 2's compliment to decimal value..?

Prashant Neginahal
Ranch Hand

Joined: Dec 04, 2002
Posts: 76
Hi All,
byte b=127;
b<<=1;
Here b is promoted to int and multiplied by 2 and result is 254.Then it is implicitely type casted to byte and it contains
11111110bits,so in byte it represents -ve value and it is in 2's compliment form.Then, what is simplest way to find its decimal value.?

--------------<br />Prashant<br />SCJP-91%
John Lee
Ranch Hand

Joined: Aug 05, 2001
Posts: 2545
Originally posted by Prashant Neginahal:
Hi All,
byte b=127;
b<<=1;
Here b is promoted to int and multiplied by 2 and result is 254.Then it is implicitely type casted to byte and it contains
11111110bits,so in byte it represents -ve value and it is in 2's compliment form.Then, what is simplest way to find its decimal value.?

b = 11111110
deduct 1: 11111101
switch bite: 00000010
so, | b | = 00000010 = 2
so, b = -2
there is no easy way, just follow the steps here. Of course, this is not diffficult at all.
Karthik Balasubramanian
Ranch Hand

Joined: Dec 13, 2002
Posts: 43
Hi Don,
Why does this undergo all this process?
byte b=127;
b<<=1;
b = 01111111
converted to int
0000 0000 0000 0000 0000 0000 0111 1111
<<1
0000 0000 0000 0000 0000 0000 1111 1110
cast to byte: 1111 1110 = 254
is it not the answer? why do we have to do those calculation as u suggest? can u please explain?
Thanks
Karthik
John Lee
Ranch Hand

Joined: Aug 05, 2001
Posts: 2545
Originally posted by Karthik Balasubramanian:
Hi Don,
Why does this undergo all this process?
byte b=127;
b<<=1;
b = 01111111
converted to int
0000 0000 0000 0000 0000 0000 0111 1111
<<1
0000 0000 0000 0000 0000 0000 1111 1110

You are correct up to this point.
Originally posted by Karthik Balasubramanian:

cast to byte: 1111 1110 = 254
is it not the answer? why do we have to do those calculation as u suggest? can u please explain?
Thanks
Karthik

For byte, the range is from -2^7 to 2^7 - 1.
So, -128 <= byte <= 127.
So 254 is out of raange for byte in the first place.
127 = 0111 1111
So, for positive, the highest is always 0. And negative is always 1 in highest bite.
The rest is according to definition. Just follow my procedure in previous post.

I agree. Here's the link: http://aspose.com/file-tools

subject: 2's compliment to decimal value..?