Developing Algorithms (JavaScript)
sunny = true;
rainy = false;
if (sunny) {
umbrella = false;
} else if (rainy) {
umbrella = true;
} else {
umbrella = false;
}
console.log(umbrella);
The code above is the same as below:
umbrella = !sunny && rainy;
console.log(umbrella);
To determine if two conditionals and booleans are the same, you can substitute the four possibilities that the two booleans (sunny and rainy) can be (listed below) into the conditional and boolean and see if both cases match:
sunny = true
, rainy = true
sunny = true
, rainy = false
sunny = false
, rainy = true
sunny = false
, rainy = false
Challenge
Using JavaScript, create an algorithm that takes in an IP address and a subnet mask and computes the network address.
Overview
As we've seen in Unit 4.1, an IP address is a 32 bit number that uniquely identifies each device. (See this for a recap). Something extra is that an IP address also comes with a subnet mask. A subnet mask is also a 32 bit number that identifies what network an IP address in in through a process that uses the bitwise AND.
In ANDing:
0 + 0 = 0
0 + 1 = 0
1 + 0 = 0
1 + 1 = 1
The following are the steps to determine the network that an IP address is in given the subnet mask:
Example: IP address: 192.168.0.1
Subnet mask: 255.255.255.0
- Convert the IP address into binary: 192.168.0.1 -> 11000000.10101000.00000000.00000001
- Convert the subnet mask into binary: 255.255.255.0 -> 11111111.11111111.11111111.00000000
- Do a bitwise AND operation on the binary IP address and subnet mask:
11000000.10101000.00000000.00000001
+11111111.11111111.11111111.00000000
=11000000.10101000.00000000.00000000
- Convert the result back to decimal: 11000000.10101000.00000000.00000000 -> 192.168.0.0
The network address is 192.168.0.0
// Wasn't able to finish, here is the start.
function Address(ipAddress, subnetMask) {
var binaryIpAddress = Binary(ipAddress);
var binarySubnetMask = Binary(subnetMask);
var networkAddressBinary = binaryIpAddress & binarySubnetMask;
var networkAddress = Decimal(networkAddressBinary);
return networkAddress;
}
function Decimal(binary) {
var binaryOctets = binary.match(/.{1,8}/g);
var octets = binaryOctets.map(function(binaryOctet) {
return parseInt(binaryOctet, 2);
});
return octets.join(".");
}
var ipAddress = "192.168.0.1";
var subnetMask = "255.255.255.0";
var networkAddress = Address(ipAddress, subnetMask);
console.log(networkAddress);