Search code examples
javacompiler-errors

Possible lossy conversion from long to int, can't find error


In this code I keep getting:

 error: incompatible types: possible lossy conversion from long to int
        rem = num%16; 
 1 error

This is the code im working with currently.

public class BaseConverter{

public static String convertToBinary(long num){
    long binary[] = new long[40];
    int index = 0;
    while(num > 0){
        binary[index++] = num%2;
        num = num/2;
    }
    for(int i = index-1; i>= 0;i--){
        System.out.print(binary[i]);
    }
}
public static String convertToHexadecimal(long num){
    int rem;
    
    // For storing result
    String str=""; 

    // Digits in hexadecimal number system
    char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

    while(num>0)
    {
        rem = num%16; 
        str = hex[rem]+str; 
        num = num/16;
    }
}
}

Basically, this code is supposed to help me setup for another program which calls the static methods. But I can't compile because of this error.


Solution

  • Your problem is on the line rem = num%16; where you are assigning a value of type long to a variable of type int.

    The general rule is that the result of applying one of the arithmetic operators is the larger of the two types that are being operated on. In the words of the Java Language Specification, section 15.17 ,

    The type of a multiplicative expression is the promoted type of its operands.

    Therefore, the expression num%16 has type long, because num has type long; even though its value will always be between -15 and 15. It's an error to assign a long expression to an int variable, without explicitly casting it.

    You could write

    rem = (int) num % 16;
    

    to avoid this error.