Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum types in hex are returning wrong values using Java?

Tags:

java

hex

I am using the following enum types in the code below:

public static enum PanelType
 {
   PAS8((byte)0xA6), PAS83((byte)0xA7);

  private byte code;

  private PanelType(byte code)
  {
   this.code=code;
  }

  public byte getCode(){
   return code;
  }
 }

However, when I'm trying to use it here in my method:

 for (PanelType type:PanelType.values())
 {
   if (decoded[3]==type.getCode())
   return type;
 }

I am returning the incorrect value for the: type.getCode() method. It's returning -90 instead of 166, which is what I'm expecting.

I know that FFFF FFFF FFFF FFA6 = -90, but why does 0xA6 get returned as negative number ?

like image 916
Datenshi Avatar asked Dec 15 '25 12:12

Datenshi


1 Answers

bytes have a maximum value of 127 and a minimum value of -128. 0xA6 is 166 in decimal, so there is an overflow:

-128 + (166 - 127 - 1) == -90
like image 117
arshajii Avatar answered Dec 17 '25 02:12

arshajii