Forum Stats

  • 3,838,749 Users
  • 2,262,397 Discussions
  • 7,900,750 Comments

Discussions

Cast Operator

GC17
GC17 Member Posts: 1
edited Jun 11, 2018 9:03PM in Java Programming

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!

jwentingmanaged BEANrpc1

Answers

  • Unknown
    edited Jun 11, 2018 9:03PM
    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.
    jwentingmanaged BEANrpc1
This discussion has been closed.