^as XOR operator&is AND operator|is OR operator&&and||are short-circuit operators.
- 2's complement represent negative number
xas its(abs(x) - 1)binary format, then flip each0and1bit.
The ones' complement of a binary number is defined as the value obtained by inverting all the bits in the binary representation of the number (swapping 0s for 1s and vice versa). The ones' complement of the number then behaves like the negative of the original number in some arithmetic operations.
| Bits | unsigned value | 1's |
|---|---|---|
| 0000 0001 | 1 | 1 |
| 0000 0010 | 2 | 2 |
| 0000 0000 | 0 | 0 |
| 0111 1110 | 126 | 126 |
| 0111 1111 | 127 | 127 |
| 1000 0000 | 128 | −127 |
| 1000 0001 | 129 | −126 |
| 1111 1101 | 253 | −2 |
| 1111 1110 | 254 | −1 |
| 1111 1111 | 255 | −0 |
https://en.wikipedia.org/wiki/Ones%27_complement
- 2's complement can be represent by 1's then add 1
invert(x) + 1ex:(111)
^is XOR operator for each bits. ex:100 ^ 101 == 001|is OR operator&is AND operator~is bitwise complement operator, ex:~1000 ==
>>signed right shift, shifted bits will moved, and highest signed bit will preserve.
1001 >> 1 === 1100
- o.w.
>>>shift ops will prepend back0in all cases, ex:>>>,<<. >>represent as divide by2^n,<<as multiply by2^n
for data type's size is shorter than int ex: byte, char, or short, bitwise opertor will be type conversion to int, which may leads unexpected error:
byte i = -2
i >>> 1
// expect 11111110 => 01111111 => 127
// but since i upcast to int, actual value is 2147483647so for unary operator byte, char, or short will be cast to int. but for binary operator, rules will be applied in order:
- if any operand is
double, both cast todouble - if any operand is
float, bot cast tofloat - if any operand is
long, bot cast tolong - o.w. cast to
int
To ensure we only want to use operator as byte, short, char, we can type casrting it:
byte i = -2;
i = (byte) (i >> 1);
// i == -1But it might raise overflow issue, ex:
int i;
byte b;
i = 199;
b = (byte) i;
// -57
// bits over value 127 are truncated.- literals ex:
1,-1,298will be type casting tointby default, floating number ex:1.23will bedouble
list by its level:
++,--, unary+,-as positive, negative sign,~,!,(type casting)=> R*,/,%=> L+,-, string concat+=> L>>,>>>,<<=> L<,<=,>,>=,instanceof=> L==,!==> L&=> L^=> L|=> L&&=> L||=> L?:ternary operator => R=,*=,/=,%=,+=,-=,<<=,>>=,>>>=,&=,|=,^=assignment operators => R
- if condition not hold, the corresponding expression will not be excuted:
int i, j = 17;
i = j % 2 == 1 ? 2 : j++
// j++ will not meet, not executed though have high precedence.- type castign rule for 2nd and 3rd expressions:
- for
? x : y, ifxandyhave same return type, keep return result as same type. - for
? x : y, ifxisbyteandyisshorttype, keep return result as most extended type, so to beshort. - for
? x : y, ifxisbyteandyis an expression by integer literals (1) asint, if result is fall into the range ofbyte, will return asbyte. - o.w. follow above binary operators type casting rules.