Fix binary to octal conversion

This commit is contained in:
obelisk0114 2019-07-15 17:22:02 -07:00
parent acb40ef3b0
commit 48537fc27c

View File

@ -16,6 +16,7 @@ public class BinaryToOctal {
*/ */
public static void main(String args[]) { public static void main(String args[]) {
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
System.out.println("Input the binary number: ");
int b = sc.nextInt(); int b = sc.nextInt();
System.out.println("Octal equivalent: " + convertBinaryToOctal(b)); System.out.println("Octal equivalent: " + convertBinaryToOctal(b));
sc.close(); sc.close();
@ -26,18 +27,24 @@ public class BinaryToOctal {
* This method converts a binary number to * This method converts a binary number to
* an octal number. * an octal number.
* *
* @param b The binary number * @param binary The binary number
* @return The octal number * @return The octal number
*/ */
public static int convertBinaryToOctal(int b) { public static String convertBinaryToOctal(int binary) {
int o = 0, r = 0, j = 1; String octal = "";
while (b != 0) { int currBit = 0, j = 1;
r = b % 10; while (binary != 0) {
o = o + r * j; int code3 = 0;
j = j * 2; for (int i = 0; i < 3; i++) {
b = b / 10; currBit = binary % 10;
binary = binary / 10;
code3 += currBit * j;
j *= 2;
}
octal = code3 + octal;
j = 1;
} }
return o; return octal;
} }
} }