Advertisement
dimipan80

Decimal to Hexadecimal

Aug 17th, 2014
282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.31 KB | None | 0 0
  1. /* Write a program that enters a positive integer number
  2.  * and converts and prints it in hexadecimal form. */
  3.  
  4. import java.util.Scanner;
  5.  
  6. public class _05_DecimalToHexadecimal {
  7.  
  8.     public static void main(String[] args) {
  9.         // TODO Auto-generated method stub
  10.         Scanner scan = new Scanner(System.in);
  11.         System.out.print("Enter a positive Integer number: ");
  12.         int decimalNum = scan.nextInt();
  13.  
  14.         // Short variants:
  15.         // String hexadecimalStr =
  16.         // Integer.toHexString(decimalNum).toUpperCase();
  17.         //
  18.         // or:
  19.         // String hexadecimalStr = String.format("%X", decimalNum);
  20.  
  21.         // Custom variant, also works with negative Integers:
  22.         String hexadecimalStr = "";
  23.         do {
  24.             int rights4BitsValue = decimalNum & 15;
  25.             String hexadecimalSymb = convert4BitsValueToHexadecimalSymbol(rights4BitsValue);
  26.             hexadecimalStr = hexadecimalSymb + hexadecimalStr;
  27.             decimalNum >>>= 4;
  28.         } while (decimalNum != 0);
  29.  
  30.         System.out.printf("That number in Hexadecimal system is: %s !%n",
  31.                 hexadecimalStr);
  32.     }
  33.  
  34.     private static String convert4BitsValueToHexadecimalSymbol(int bitsValue) {
  35.         switch (bitsValue) {
  36.         case 10:
  37.             return "A";
  38.         case 11:
  39.             return "B";
  40.         case 12:
  41.             return "C";
  42.         case 13:
  43.             return "D";
  44.         case 14:
  45.             return "E";
  46.         case 15:
  47.             return "F";
  48.         default:
  49.             return "" + bitsValue;
  50.         }
  51.     }
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement