Why does bitwise AND of two short values result in an int value in Java?

后端 未结 5 1889
情话喂你
情话喂你 2020-12-07 02:10
short permissions = 0755;
short requested = 0700;
short result = permissions & requested; 

I get a compiler error:

error possib         


        
5条回答
  •  独厮守ぢ
    2020-12-07 03:05

    The operands to the & operator will be promoted to int, and therefore the result is int, which will have to be casted to short if you want to store it in result. I don't think it should be a performance penalty unless the compiler is bad at generating code.

    From http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.22.1:

    When both operands of an operator &, ^, or | are of a type that is convertible (§5.1.8) to a primitive integral type, binary numeric promotion is first performed on the operands (§5.6.2).

    From http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#170983:

    [...] Otherwise, both operands are converted to type int.

提交回复
热议问题