Gangmax Blog

A Java Expression

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
2
3
4
5
6
System.out.println(10 & 12);
// returns 8

// The binary value of 10 is 1010,
// The binary value of 12 is 1100,
// So the result is 1000.

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
2
3
4
5
6
7
a = 5 = 0101 (In Binary)

Bitwise Complement Operation of 5

~ 0101
________
1010 = 10 (In decimal)

The purpose of the original expression is to make it return the following values:

1
2
3
4
If the last 2 bits is "00", return 0;
if the last 2 bits is "01", return 3;
if the last 2 bits is "10", return 2;
if the last 2 bits is "11", return 1;

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.

Comments