Saturday, February 9, 2013

convert decimal tohexadecima

9:24 AM



package stack;
import java.util.Scanner;

public class decimal2hexa extends Stack {
    String digits = "0123456789ABCDEF";
    int decimal;
    int size;

    public decimal2hexa(int n) {
        super(n);
        System.out.println("Enter nonnegative integer :");
        Scanner input = new Scanner(System.in);
        decimal = input.nextInt();
        size = 0;
    }
    /**
     * push the value to stack
     */
    public void setHex2Stack() {
        if (decimal == 0) {
            push(0);
        }
        while (decimal > 0) {
            int digit = decimal % 16;
            push(digits.charAt(digit));
            decimal = decimal / 16;
            size++;
        }
    }
    /**
     * @return hexadecimal string value
     */
    public String getHexa() {
        String h = "";
        while (!isEmpty()) {
            h = h + pop();
        }
        return h;
    }
    public static void main(String args[]) {
        decimal2hexa d = new decimal2hexa(16);
        d.setHex2Stack();
        d.print();
        System.out.println("Hexadecimal : " + d.getHexa());
        decimal2hexa d2 = new decimal2hexa(16);
        d2.setHex2Stack();
        d2.print();
        System.out.println("Hexadecimal : " + d2.getHexa());
    }
}
Output of this program :

run:
Enter nonnegative integer :
31
Contents of Stack :
F | 1 | 
Hexadecimal : 1F
Enter nonnegative integer :
256
Contents of Stack :
0 | 0 | 1 | 
Hexadecimal : 100
BUILD SUCCESSFUL (total time: 9 seconds)

Written by

We are Creative Blogger Theme Wavers which provides user friendly, effective and easy to use themes. Each support has free and providing HD support screen casting.

0 comments:

Post a Comment

 

© 2013 CSC. All rights resevered. Designed by Templateism

Back To Top