Search code examples
javajava-melwuit

How to get an int from a byte in J2ME?


I retrieved the backgroundTransparency of a LWUIT Button , and it returns a byte datatype data. I want this byte variable to be converted to an int variable. How to do that ?


Solution

  • Fernando's answer is 100% correct but is still slightly misleading e.g.:

     byte b = (byte)0xff;
     int intVar = b;
    
     boolean thisIsFalse = intVar == 0xff;
    

    That might surprise most people at first glance but the logic is actually simple. 0xff is a negative number for a byte but a positive number for an int (this is also true in Java SE). The solution is to change the code from above to something that will convert to int "properly":

     int intVal = b & 0xff;
     boolean thisIsTrue = intVar == 0xff;
    

    This will solve the issue there but you should still be aware that:

     boolean thisIsFalse = intVar == b;
     boolean thisIsTrue = intVar == (b & 0xff);