d
package com.javarush.task.pro.task09.task0908;
import java.util.regex.Pattern;
/*
Двоично-шестнадцатеричный конвертер
*/
public class Solution {
public static void main(String[] args) {
String binaryNumber = "100111010000";
System.out.println("Двоичное число " + binaryNumber + " равно шестнадцатеричному числу " + toHex(binaryNumber));
String hexNumber = "9d0";
System.out.println("Шестнадцатеричное число " + hexNumber + " равно двоичному числу " + toBinary(hexNumber));
}
public static String toHex(String binaryNumber) {
String str = "";
if (binaryNumber == null || binaryNumber.isEmpty() || !Pattern.matches("[0-1]+", binaryNumber)) {
return str;
}
if (binaryNumber.length() % 4 != 0)
{
for (int i = binaryNumber.length() % 4; i < 4; i++) {
binaryNumber = binaryNumber + "0";
}
}
for (int i = 0; i < binaryNumber.length(); i+=4) {
int sum = 0;
for (int j = 0; j < 4; j++) {
sum+= (binaryNumber.charAt(i + j) - '0')*(int)Math.pow(2, 3 - j);
}
if (sum > 9 && sum < 16)
str = str + ((char)(sum - 10 + 'a'));
else
str = str + sum;
}
return str;
}
public static String toBinary(String hexNumber) {
String str = "";
int number;
if (hexNumber == null || hexNumber.isEmpty() || !Pattern.matches("[0-9a-f]+", hexNumber)) {
return str;
}
for (int i = 0; i < hexNumber.length(); i++) {
char tmp = hexNumber.charAt(i);
if (tmp >= 'a' && tmp <= 'f') {
number = (tmp - 'a') + 10;
}
else{
number = tmp - '0';
}
for (int j = 0; j < 4; j++) {
if (number >= (int)Math.pow(2, 3 - j)) {
str = str + "1";
number = number - (int)Math.pow(2, 3 - j);
}
else {
str = str + "0";
}
}
}
return str;
}
}