Java Program To Convert Decimal To Hexadecimal

How to convert a decimal number into hex in java

To convert a decimal number to a hexadecimal number, use the following algorithm.

toHex(x)

  1. let S be the stack
  2. q = x / 16 and r = x % 16 // where q and r are the quotient and
    remainder
  3. S.push(q) if q > 0 
  4. S.push(r) 
  5. while (top element e > 15)
    • pop out top element e
    • q = e / 16
    • r = e % 16
    • S.push(q)
    • S.push(r)
  6. let C is the char list
  7. while (stack is not empty)
    • e = pop out top element
    • if e is lie between 10 to 15 replace it with its corresponding hex digit
    • C.append(e)
  8. return C.toString()
public class Main {

 public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int decimal = scan.nextInt();
        System.out.println(toHex(decimal));
 }



     /**
     * Convert To Hex
     */
    public static String toHex(final int X) {
        final Stack<Integer> S = new Stack<>();
        int q = X / 16;
        int r = X % 16;

        S.push(r);
        if (q > 0) S.push(q);


        while (S.peek() > 15) {
            int e = S.pop();
            q = e / 16;
            r = e % 16;

            S.push(r);
            S.push(q);
        }

        StringBuilder C = new StringBuilder();
        while (!S.isEmpty()) {
            int e = S.pop();
            switch (e) {
                case 10 -> C.append('A');
                case 11 -> C.append('B');
                case 12 -> C.append('C');
                case 13 -> C.append('D');
                case 14 -> C.append('E');
                case 15 -> C.append('F');
                default -> C.append(e);
            }
        }

        return C.toString();
    }
}
Share this Post

Leave a Reply

Your email address will not be published. Required fields are marked *