Binary To Octal Algorithm
The Binary to Octal Algorithm is a simple yet efficient method to convert binary numbers (base 2) into their corresponding octal numbers (base 8). This algorithm works by grouping the binary digits into sets of three, starting from the least significant digit (rightmost) and moving towards the most significant digit (leftmost). If the last group has less than three digits, zeros are added to complete the group. Then, each group of three binary digits is replaced by their equivalent octal digit, resulting in an octal number. Since there are only eight unique octal digits (0 to 7), each group of three binary digits (ranging from 000 to 111) can easily be converted into a single octal digit.
To illustrate the Binary to Octal Algorithm, let's consider the binary number 11011010. First, we group the binary digits into sets of three, starting from the right: 110, 110, 010. Notice that in this case, we didn't need to add any zeros to complete the last group. Next, we convert each group of three binary digits into their corresponding octal digit: 6, 6, 2. Thus, the octal representation of the given binary number is 662. This algorithm is particularly useful when working with larger binary numbers, as it simplifies the conversion process into a more compact and manageable form, making it easier to read and understand.
package Conversions;
import java.util.Scanner;
/**
* Converts any Binary number to an Octal Number
*
* @author Zachary Jones
*/
public class BinaryToOctal {
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Input the binary number: ");
int b = sc.nextInt();
System.out.println("Octal equivalent: " + convertBinaryToOctal(b));
sc.close();
}
/**
* This method converts a binary number to
* an octal number.
*
* @param binary The binary number
* @return The octal number
*/
public static String convertBinaryToOctal(int binary) {
String octal = "";
int currBit = 0, j = 1;
while (binary != 0) {
int code3 = 0;
for (int i = 0; i < 3; i++) {
currBit = binary % 10;
binary = binary / 10;
code3 += currBit * j;
j *= 2;
}
octal = code3 + octal;
j = 1;
}
return octal;
}
}