In the following snippet consider replacing line 8 with commented equivalent
1. private static String ipToText(byte[] ip) {
2. StringBuffer result = new StringBuffer();
3.
4. for (int i = 0; i < ip.length; i++) {
5. if (i > 0)
6. result.append(".");
7.
8. result.append(ip[i]); // compare with result.append(0xff & ip[i]);
9. }
10.
11. return result.toString();
12. }
.equals() test confirms that adding 0xff does not change anything. Is there a reason for this mask to be applied?
bytein Java is a number between −128 and 127 (signed, like every integer in Java (except forcharif you want to count it)). By anding with0xffyou’re forcing it to be a positiveintbetween 0 and 255.It works because Java will perform a widening conversion to
int, using sign extension, so instead of a negativebyteyou will have a negativeint. Masking with0xffwill leave only the lower 8 bits, thus making the number positive again (and what you initially intended).You probably didn’t notice the difference because you tested with a
byte[]with only values smaller than 128.Small example:
This prints
showing the difference between what’s in the
byte, what went into the byte when it still was anintand what the result of the&operation is.