Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Cast Operator

GC17Jun 11 2018 — edited Jun 11 2018

Hello everyone!

I have a question regarding cast operators and data loss, specifically converting from int to byte.

If I start out with 200 as an int variable, and convert it to a byte shouldn't I get -72, since the first binary digit of value "128" is used to determine the sign. For some reason, I am not getting -72, but -56 instead. Could someone help me resolve this discrepancy?

Thank you very much!

Comments

unknown-7404

Could someone help me resolve this discrepancy?

Sure - once you SHOW US:

1. WHAT you do

2. HOW you do it

3. WHAT results you get

4. WHAT results you expected to get

We can't comment on your code or process until we see it.

If I start out with 200 as an int variable, and convert it to a byte shouldn't I get -72, since the first binary digit of value "128" is used to determine the sign. For some reason, I am not getting -72, but -56 instead. Could someone help me resolve this discrepancy?

If you want to understand binary then you need to go 'step by step' and start from the beginning.

You can understand why you get -56 if you start with 0 and keep subtracting one and looking at the binary value

00000000   - 0

11111110    - -1

11111101   - -2

. . .

11001110 - -50

. . .

11001000 - -56 if you interpret this as a signed BYTE value. But an an int it is 00000000 00000000 00000000 11001000 which is 200

if you add minus 56 to 256 what do you get? Did you get 200?

Narrowing conversions (taking that 4 byte int 000000C8) simply take the low order bits as is.

See the Java Language Spec for the full explanation of how narrowing conversions work

https://docs.oracle.com/javase/specs/jls/se10/html/jls-5.html#jls-5.1.3

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

1 - 2
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Jul 9 2018
Added on Jun 11 2018
2 comments
312 views