Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a program that enters a positive integer number
- * and converts and prints it in hexadecimal form. */
- import java.util.Scanner;
- public class _05_DecimalToHexadecimal {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Scanner scan = new Scanner(System.in);
- System.out.print("Enter a positive Integer number: ");
- int decimalNum = scan.nextInt();
- // Short variants:
- // String hexadecimalStr =
- // Integer.toHexString(decimalNum).toUpperCase();
- //
- // or:
- // String hexadecimalStr = String.format("%X", decimalNum);
- // Custom variant, also works with negative Integers:
- String hexadecimalStr = "";
- do {
- int rights4BitsValue = decimalNum & 15;
- String hexadecimalSymb = convert4BitsValueToHexadecimalSymbol(rights4BitsValue);
- hexadecimalStr = hexadecimalSymb + hexadecimalStr;
- decimalNum >>>= 4;
- } while (decimalNum != 0);
- System.out.printf("That number in Hexadecimal system is: %s !%n",
- hexadecimalStr);
- }
- private static String convert4BitsValueToHexadecimalSymbol(int bitsValue) {
- switch (bitsValue) {
- case 10:
- return "A";
- case 11:
- return "B";
- case 12:
- return "C";
- case 13:
- return "D";
- case 14:
- return "E";
- case 15:
- return "F";
- default:
- return "" + bitsValue;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement