请记住,当我们将八进制转换为十进制时,我们一次获取了3个二进制数字。将使用类似的方法,在这里,对于每3位数字,我们有一个对应的数字,如在八进制系统中,我们有从0到’R-1’的数字,其中R代表数字系统的基值。顾名思义,在八进制系统中,R等于8。因此,该数字如下:0、1、2、3、4、5、6、7。
现在,借助HashMaps转换一件东西的过程很明显,一种方式或其他二进制等价物和八进制等价物将在我们的HashMap中充当键值对。
Octal | Binary |
---|---|
0 | 000 |
1 | 001 |
2 | 010 |
3 | 011 |
4 | 100 |
5 | 101 |
6 | 110 |
7 | 111 |
算法:
- 将二进制数转换为十进制数。
- 使用HashMap,我们将每个位及其十进制值进行映射。
- 找到该位时,它将与十进制数字对应
- 打印并显示该数字的八进制等效项。
插图:
Input 1 : 1011
Output 1 : 13
Input 2 : 1000
Output 2 : 10
执行:
例子
Java
// Java Progeram to Convert Binary Number to Octal Number
// Importing all utility classes
import java.util.*;
// Main class
pubic class GFG {
// Mehod 1
// Helper method
public static void octal(String s)
{
// Here binary number is representedd by string 's'
// over which standard length() method is computed
// to get the length of binary number
// Appending 2 zeros if bnary numbers leaves
// remainder as 1 after dividing with 3
if (s.length() % 3 == 1) {
// Append two zeros to it
s = "00" + s;
}
// If binary string number length after equals 2
else if (s.length() % 3 == 2) {
// Concatinate string by adding 1 zero to it
s = "0" + s;
}
// Creating an object of HashMap
// Declaring object of String and Integer types
HashMap hm = new HashMap<>();
// Adding elements to the object created above
// using the put() method
// Adding elements(key-value) pairs to given object
// 000 in binary system -> 0 in octal system
// 001 in binary system -> 1 in octal system
// Similarly adding for 0 to N-1 (N=8 for octal)
hm.put("000", 0);
hm.put("001", 1);
hm.put("010", 2);
hm.put("011", 3);
hm.put("100", 4);
hm.put("101", 5);
hm.put("110", 6);
hm.put("111", 7);
// Creating and declaring a string array
String[] part = new String[3];
int t = 0;
// Iterating over the binary number digits
for (int i = 0; i < s.length(); i = i + 3) {
// Checking for substring in an binary number
// gigit array
String bypart = s.substring(i, i + 3);
part[t] = bypart;
// If found
if (hm.containsKey(part[t])) {
// Getting the part to be matched for
// its corresponding octal numbers
System.out.print(hm.get(part[t]));
}
// Incrementing the counter
t++;
}
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Display message
System.out.print("Enter the binary number to be converted : ");
// Binary number to be converted
// Custom entry
String s = 011;
// Calling the method1 octal() over the
// above input entered number
octal(s);
// Display message
System.out.print("Octal equivalent : ");
}
}
输出:
Enter the binary number to be converted : 011
Octal equivalent : 3