Basically 2 questions:
1) I do not understand how we compare two byte[]. What does it return. I'm looking for a detailed description of the calculation
2) To display the byte[] as a binary String there are parts in the code that I can't find the meaning of. What exactly are we doing in the print()??
As you can tell I just copied and pasted the answer without any understanding, obviously ;-).
package com.codegym.task.task21.task2101;
/*
Determine the network address
*/
public class Solution {
public static void main(String[] args) {
byte[] ip = new byte[]{(byte) 192, (byte) 168, 1, 2};
byte[] mask = new byte[]{(byte) 255, (byte) 255, (byte) 254, 0};
byte[] netAddress = getNetAddress(ip, mask);
print(ip); //11000000 10101000 00000001 00000010
print(mask); //11111111 11111111 11111110 00000000
print(netAddress); //11000000 10101000 00000000 00000000
}
public static byte[] getNetAddress(byte[] ip, byte[] mask) {
byte[] netAddress = new byte[4];
//how does this work?
//we compare each bit of the first byte[] with the first bit of the second byte[]
//what does this return?
//clueless as what we are comparing
for (int i = 0; i < netAddress.length; i++) {
netAddress[i] = (byte) (ip[i] & mask[i]);
}
return netAddress;
}
public static void print(byte[] bytes) {
for(byte bit : bytes) {
//replace(' ', '0') this add zero's if the binaryString is shorter than 8? not sure
//what does this do? (bit & 0xFF)
String bitResult = String.format("%8s", Integer.toBinaryString(bit & 0xFF)).replace(' ', '0');
//we convert the bit into a string of chars of 1 or 0??
System.out.print(bitResult + " ");
}
System.out.println();
}
}