forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryToOctal.java
More file actions
26 lines (24 loc) · 858 Bytes
/
BinaryToOctal.java
File metadata and controls
26 lines (24 loc) · 858 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.examplehub.conversions;
public class BinaryToOctal {
/**
* Convert binary string to octal string.
*
* @param binaryString the binary string.
* @return octal string of a binary string.
*/
public static String toOctal(String binaryString) {
StringBuilder builder = new StringBuilder(binaryString);
if (binaryString.length() % 3 != 0) {
// just wok on jdk 11+
// builder.append("0".repeat(3 - binaryString.length() % 3));
binaryString =
(binaryString.length() % 3 == 1 ? builder.insert(0, "00") : builder.insert(0, "0"))
.toString();
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < binaryString.length() / 3; i++) {
result.append(BinaryToDecimal.toDecimal(binaryString.substring(3 * i, 3 * i + 3)));
}
return result.toString();
}
}