Converter número binário em octal usando HashMap em Java
Lembre-se de que, enquanto estávamos convertendo octal em decimal, estávamos pegando 3 dígitos binários por vez. Uma abordagem semelhante será usada onde aqui para cada 3 dígitos temos um número correspondente, como no sistema octal, temos números de 0 a 'R-1', onde R representa o valor base do sistema numérico. Como o nome sugere, em um sistema numérico octal, R é equivalente a 8. Portanto, o número é o seguinte: 0,1,2,3,4,5,6,7.
Agora, indo em virtude de HashMaps na conversão de uma coisa, fica claro a partir daqui que aquela forma ou outro equivalente binário e equivalente octal irão atuar como pares de valores-chave em nosso HashMap.
Octal | Binário |
---|---|
0 | 000 |
1 | 001 |
2 | 010 |
3 | 011 |
4 | 100 |
5 | 101 |
6 | 110 |
7 | 111 |
Algoritmo:
- Converta o número binário em um número decimal.
- Usando o HashMap, mapeamos cada bit com seus valores decimais.
- Quando o bit é encontrado, ele mapeia com o número decimal
- Imprime e exibe o equivalente octal do número.
Ilustração:
Input 1 : 1011 Output 1 : 13 Input 2 : 1000 Output 2 : 10
Implementação:
Exemplo
// Java Program to Convert Binary Number to Octal Number
// Importing all utility classes
import java.util.*;
// Main class
pubic class GFG {
// Method 1
// Helper method
public static void octal(String s)
{
// Here binary number is represented by string 's'
// over which standard length() method is computed
// to get the length of binary number
// Appending 2 zeros if binary 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) {
// Concatenate string by adding 1 zero to it
s = "0" + s;
}
// Creating an object of HashMap
// Declaring object of String and Integer types
HashMap<String, Integer> 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
// digit 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 : ");
}
}
Saída:
Enter the binary number to be converted : 011 Octal equivalent : 3
As postagens do blog Acervo Lima te ajudaram? Nos ajude a manter o blog no ar!
Faça uma doação para manter o blog funcionando.
70% das doações são no valor de R$ 5,00...
Diógenes Lima da Silva