sk89
sk89

Reputation: 51

Java : Operators and Typecasting

long value = 0x88888888 ;
int i = (int) (value & 0xff);

How does the above evaluation of expression take place? Is it

int i = (int)value & (int)0xff ;

or does the bitwise and operation gets evaluated first? I am getting confused :-|

Upvotes: 1

Views: 114

Answers (3)

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

Lets take a look at the bytecode:

 public static void main(java.lang.String[]);
    Code:
    0: ldc2_w        #35                 // long -2004318072l
    3: lstore_1
    4: lload_1
    5: ldc2_w        #37                 // long 255l
    8: land
    9: l2i
   10: istore_3
   11: return
}

as you can see the hexadecimal 0xff is first converted to long and then use the bitwise and to the value by masking it with the 0xff after it is then converted to int

  • lload_1 load a long value from a local variable 1

  • ldc2_w push a constant #index from a constant pool (double or long) onto the stack

  • land bitwise and of two longs
  • l2i convert a long to a int

Upvotes: 5

Deepanshu J bedi
Deepanshu J bedi

Reputation: 1530

First (value & 0xff); will be solved. i.e value(bitwise and)0xff. then the resultant will be converted to int value using type casting int i = (int) (value & 0xff);

Upvotes: 0

Eran
Eran

Reputation: 393841

First the bitwise operation is evaluated as an operation on longs (the parenthesis guarantee it). Then the result is cast to int.

Upvotes: 3

Related Questions