Convert Decimal to Hexadecimal Java Program
Java Program:
import java.util.Scanner;
public class hTd {
public static int parseHex(String hexString) {
if (hexString == null)
return 0;
int Power = 0;
int Total = 0;
for (int i =
hexString.length()-1; i >=0; i--) {
char c =
hexString.charAt(i);
int Val = 0;
switch (c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
Val
= Integer.parseInt(c
+ "");
break;
case 'A': case 'a':
Val
= 10;
break;
case 'B': case 'b':
Val
= 11;
break;
case 'C': case 'c':
Val
= 12;
break;
case 'D': case 'd':
Val
= 13;
break;
case 'E': case 'e':
Val
= 14;
break;
case 'F': case 'f':
Val
= 15;
break;
default:
System.err.println("invalid
character: " + c);
Val
= 0;
break;
}
Total
+= (Math.pow(16, Power) * Val);
Power++;
}
return
Total;
}
public static void main(String[] args)
{
System.out.print("enter number
to convert from decimal to hexadecimal: ");
Scanner
input = new Scanner(System.in);
String
in=input.nextLine();
System.out.print("Hexadecimal
number is : "+parseHex(in));
}
}
No comments:
Post a Comment