decimal to binary/octa/hexadecimal conversion

Here decimal to binary/octa/hexa decimal conversions are shown.

Algorithm is simple provided we should make use of the stack (stack implementation) to put the coefficients.

public class DecimalConversion {
	TNStack st = new TNStack(30);
	private static HashMap<Integer, String> hm = new HashMap<Integer, String>();
	
	/**
	 * converts number to given base
	 * @param number
	 * @param base
	 */
	public void decimalToXXXConversion(int number, int base) {
		System.out.println("Number "+number+" in base "+base+" is: ");
		while(number>0) {
			st.push(number%base);
			number = number/base;
		}
		
		while(!st.isEmpty()) {
			int n = st.pop();
			if(n>9) {
				String str = hm.get(n);
				System.out.print(str);
			} else {
				System.out.print(n);
			}
		}
		System.out.println();
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		DecimalConversion dc = new DecimalConversion();
	
		// decimal to binary conversion
		dc.decimalToXXXConversion(100, 2);

		// decimal to octal conversion
		dc.decimalToXXXConversion(100, 8);
				
		// decimal to hexadecimal conversion
		hm.put(10, "A");
		hm.put(11, "B");
		hm.put(12, "C");
		hm.put(13, "D");
		hm.put(14, "E");
		hm.put(15, "F");
		dc.decimalToXXXConversion(10012, 16);	
	}
}

Output:
Number 100 in base 2 is:
1100100
Number 100 in base 8 is:
144
Number 10012 in base 16 is:
271C

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Mawazo

Mostly technology with occasional sprinkling of other random thoughts

amintabar

Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates

Diabolical or Smart

Nitwit, Blubber, Oddment, Tweak !!

javaproffesionals

A topnotch WordPress.com site

thehandwritinganalyst

Just another WordPress.com site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey