2019-05-09 19:32:54 +08:00
|
|
|
package Conversions;
|
|
|
|
|
2017-04-21 02:56:21 +08:00
|
|
|
import java.util.Scanner;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Converts any Binary number to an Octal Number
|
|
|
|
*
|
2019-05-09 19:32:54 +08:00
|
|
|
* @author Zachary Jones
|
2017-04-21 02:56:21 +08:00
|
|
|
*/
|
|
|
|
public class BinaryToOctal {
|
2019-05-09 19:32:54 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Main method
|
|
|
|
*
|
|
|
|
* @param args Command line arguments
|
|
|
|
*/
|
|
|
|
public static void main(String args[]) {
|
|
|
|
Scanner sc = new Scanner(System.in);
|
2019-07-16 08:22:02 +08:00
|
|
|
System.out.println("Input the binary number: ");
|
2019-05-09 19:32:54 +08:00
|
|
|
int b = sc.nextInt();
|
|
|
|
System.out.println("Octal equivalent: " + convertBinaryToOctal(b));
|
|
|
|
sc.close();
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* This method converts a binary number to
|
|
|
|
* an octal number.
|
|
|
|
*
|
2019-07-16 08:22:02 +08:00
|
|
|
* @param binary The binary number
|
2019-05-09 19:32:54 +08:00
|
|
|
* @return The octal number
|
|
|
|
*/
|
2019-07-16 08:22:02 +08:00
|
|
|
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;
|
2019-05-09 19:32:54 +08:00
|
|
|
}
|
2019-07-16 08:22:02 +08:00
|
|
|
return octal;
|
2019-05-09 19:32:54 +08:00
|
|
|
}
|
2017-04-21 02:56:21 +08:00
|
|
|
|
|
|
|
}
|