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:

# 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
Sheriff
Posts: 23295
125
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
Sheriff
Posts: 23295
125
• 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

Rancher
Posts: 2240
28
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
Sheriff
Posts: 23295
125
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