This week's book giveaways are in the Refactoring and Agile forums.We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# converting int to byte ?

Anto Telvin
Ranch Hand
Posts: 113
hi all
i have a code like this
int a=8666;
byte b=(byte)a;
i am getting -38 as output. But i can say only the output after it gets print.How can i determine the value before looking to the output console.how can i solve this one mentally

thanks

Henry Wong
author
Marshal
Posts: 20894
75
how can i solve this one mentally

Well, I highly doubt that you can do this one mentally, but who knows... It can be done in three steps.

1. Convert the decimal number to binary. Since this number is positive, you can just do this somewhat easily.

2. Truncate the three high order bytes. This is what the Java compiler does.

3. Convert the binary back to decimal. Unfortunately, since the sign bit is on, you will need to do this via twos-complement. (google twos complement for more information)

Henry

Henry Wong
author
Marshal
Posts: 20894
75
• 1
For example...

8666 = 0000 0000 0000 0000 0010 0001 1101 1010 (to binary)

= 1101 1010 (truncated)

= 0010 0101 (negated)
= 0010 0110 (negated plus one)
= 38 (decimal after negated plus one)
= -38 (hence, decimal original)

Henry

Ranch Hand
Posts: 728
4
It really depends on what the user wants the results to be when truncating the HO 3 bytes. 38 doesn't make any sense to me. Does he want to loose the value of the HO bit by treating that bit as the sign?
The value of the LO byte should be 218.

Henry Wong
author
Marshal
Posts: 20894
75
It really depends on what the user wants the results to be when truncating the HO 3 bytes. 38 doesn't make any sense to me. Does he want to loose the value of the HO bit by treating that bit as the sign?
The value of the LO byte should be 218.

Maybe. But that wasn't the question. The question was what happens when an int is casted to a byte. And in that case, the higher order 3 bytes are truncated. And the remaining byte is treated as a signed byte -- which in the example, is valued at -38.

Henry