Today I read the following Java expression which I didn’t get what it meant.
1 | int padding = ((size + 3) & ~(3)) - size; |
Here is the answer.
The symbol “&” denotes the bitwise AND operator. It evaluates the binary value of given numbers. The binary result of these numbers will be returned to us in base 10. When the & operator starts its operation, it will evaluate the value of characters in both numbers starting from the left. From “here“.
1 | System.out.println(10 & 12); |
The symbol “~” is unary operator for “Bitwise Complement”. It returns the one’s complement representation of the input value, i.e., with all bits inverted, which means it makes every 0 to 1, and every 1 to 0. From “here“.
1 | a = 5 = 0101 (In Binary) |
The purpose of the original expression is to make it return the following values:
1 | If the last 2 bits is "00", return 0; |
For me a more understandable(less efficient maybe?) expression to get the same result is:
1 | int padding = (4 - size % 4) % 4 |
Not sure how the expression was made and the logic behind it.