Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# 2's compliment to decimal value..?

Prashant Neginahal
Ranch Hand
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.?

John Lee
Ranch Hand
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
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
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.