[Java] Loss of Precision

  • I got these errors in my function that prints out a byte in 1's and 0's. I don't get why it's saying that there will be a loss of precision if a byte type in Java is 8 bits and I assigned exactly 8 bits to that byte type.

    ==============================================

    dcllnx17> javac PrintSimilarity.java
    ./Neighbors.java:25: possible loss of precision
    found : int
    required: byte
    byte ander = 0x80;
    ^
    ./Neighbors.java:30: possible loss of precision
    found : int
    required: byte
    ander = 0x80 >>> bit;
    ^
    2 errors


    // Name: charToBin
    // Input: a single byte
    // Output: none
    // Purpose: prints out the character input in binary
    public static void charToBin(byte theByte)
    {
    // ander = 1000 0000
    byte ander = 0x80;

    // tests each bit of input by ANDing 1 with each bit
    for(int bit = 0; bit < 8; bit++)
    {
    ander = 0x80 >>> bit;
    if((ander & theByte) == ander)
    System.out.print("1");
    else
    System.out.print("0");
    }
    }


  • try

    ander = (byte)(0x80 >>> bit);


  • You have to keep in mind that 0x80 is just another way of specifying an integer. In this case it fits in 1 byte, but to Java it's still an integer. You're trying to assign an integer (4 bytes) to a variable of the type byte (1 byte), so Java is warning you for possible loss of precision. So what you need to do is cast your integer to a byte, explicitly telling Java that you're ok with the "loss" of precision:

    byte ander = (byte) 0x80;The same thing happens on this line:
    ander = 0x80 >>> bit;You're performing a bitshift on 0x80 (an integer) which results in another integer which you are then again assigning to a byte. So here, as eirche pointed out before, you have to cast it to a byte as well.


  • That fixes the 2nd error, but the first error still remains.

    byte ander = 0x80;







  • #If you have any other info about this subject , Please add it free.#
    Your name:
    E-mail:
    Telphone:

    Your comments:


    If you have any other info about [Java] Loss of Precision , Please add it free.