File tree 1 file changed +16
-9
lines changed
1 file changed +16
-9
lines changed Original file line number Diff line number Diff line change @@ -16,6 +16,7 @@ public class BinaryToOctal {
16
16
*/
17
17
public static void main (String args []) {
18
18
Scanner sc = new Scanner (System .in );
19
+ System .out .println ("Input the binary number: " );
19
20
int b = sc .nextInt ();
20
21
System .out .println ("Octal equivalent: " + convertBinaryToOctal (b ));
21
22
sc .close ();
@@ -26,18 +27,24 @@ public static void main(String args[]) {
26
27
* This method converts a binary number to
27
28
* an octal number.
28
29
*
29
- * @param b The binary number
30
+ * @param binary The binary number
30
31
* @return The octal number
31
32
*/
32
- public static int convertBinaryToOctal (int b ) {
33
- int o = 0 , r = 0 , j = 1 ;
34
- while (b != 0 ) {
35
- r = b % 10 ;
36
- o = o + r * j ;
37
- j = j * 2 ;
38
- b = b / 10 ;
33
+ public static String convertBinaryToOctal (int binary ) {
34
+ String octal = "" ;
35
+ int currBit = 0 , j = 1 ;
36
+ while (binary != 0 ) {
37
+ int code3 = 0 ;
38
+ for (int i = 0 ; i < 3 ; i ++) {
39
+ currBit = binary % 10 ;
40
+ binary = binary / 10 ;
41
+ code3 += currBit * j ;
42
+ j *= 2 ;
43
+ }
44
+ octal = code3 + octal ;
45
+ j = 1 ;
39
46
}
40
- return o ;
47
+ return octal ;
41
48
}
42
49
43
50
}
You can’t perform that action at this time.
0 commit comments