public static String toHex(int decimalNumber) {
if (decimalNumber <=0) return "";
int i=0;
StringBuilder hex= new StringBuilder();
while ((int)(decimalNumber/Math.pow(16,i))>0)i++;
int j=i-1;
while (decimalNumber>0){
int a = (int)((decimalNumber/Math.pow(16,j)));
int b= (int)(a*Math.pow(16,j));
String c = HEX.substring(a,a+1);
hex.append(c);
decimalNumber=decimalNumber-b;
j--;
}
return hex.toString();
package en.codegym.task.pro.task09.task0907;
/*
Hexadecimal converter
*/
public class Solution {
private static final String HEX = "0123456789abcdef";
public static void main(String[] args) {
int decimalNumber = 1256;
System.out.println("Decimal number " + decimalNumber + " is equal to hexadecimal number " + toHex(decimalNumber));
String hexNumber = "4e8";
System.out.println("Hexadecimal number " + hexNumber + " is equal to decimal number " + toDecimal(hexNumber));
}
public static String toHex(int decimalNumber) {
if (decimalNumber <=0) return "";
int i=0;
StringBuilder hex= new StringBuilder();
while ((int)(decimalNumber/Math.pow(16,i))>0)i++;
int j=i-1;
while (decimalNumber>0){
int a = (int)((decimalNumber/Math.pow(16,j)));
int b= (int)(a*Math.pow(16,j));
String c = HEX.substring(a,a+1);
hex.append(c);
decimalNumber=decimalNumber-b;
j--;
}
return hex.toString();
}
public static int toDecimal(String hexNumber) {
if (hexNumber==null)return 0;
if (hexNumber.length()<1) return 0;
int decimal = 0;
for(int i=0; i<hexNumber.length(); i++){
decimal = decimal + HEX.indexOf(hexNumber.substring(i,i+1))
* (int) Math.pow(16,(hexNumber.length()-1-i));
}
return decimal;
}
}