coder2539@gmail.com

This program converts decimals to hexadecimal , octal or binary
 avatar
Coder
java
3 years ago
1.9 kB
4
Indexable
import java.util.*;
/*this java program converts a binary number to 
either hexadecimal,octal or binary
*/
public class Main
{
	public static void main(String[] args)
	{
		
		Scanner scan = new Scanner(System.in);
	try{
		System.out.print("Enter decimal number: ");
		long val = scan.nextLong();
		System.out.println("Enter number (1-3)\n1(octal)\n2(hexademicimal)\n3(Binary)");
	
		int choice = scan.nextInt();
		if(choice == 1){
	     System.out.println(val+" in octal is "+toOctal(val));
		}
		else if(choice == 2){
			System.out.println(val+" in hexadecimal is "+toHex(val));
		}else if(choice == 3){
			
			System.out.println(val+" in binary is "+toBin(val));
		}else{
			System.out.println("No such option");
		}
		}catch(InputMismatchException ex){System.err.println("invalid request");}
		}
		
	//converts to binary
	public static String toBin(long val)
	{

		String remainders=""; 
		while (val >= 1)
		{		
			remainders += val % 2;
			val /= 2;


		}
         remainders+="b0";
		return new StringBuilder(remainders).reverse().toString();
	}
    //converts to hexadecimal
	public static String toHex(Long val)
	{
		String remainder="";
		int DoubleRemainder =0;
		HashMap<Integer,String>hash = new HashMap<>(6);
		hash.put(10, "a");
		hash.put(11, "b");
		hash.put(12, "c");
		hash.put(13, "d");
		hash.put(14, "e");
		hash.put(15, "f");

		while (val >= 1)
		{
			DoubleRemainder = (int)(val % 16);
			if (DoubleRemainder >= 10)
			{
				remainder += hash.get(DoubleRemainder);	
			}
			else
			{
				remainder += val % 16;		 
			}
			val /= 16;
		}
          remainder +="x0";

		return new StringBuilder(remainder).reverse().toString();
	}
	//converts to octal
	public static String toOctal(long val){
		
		String remainder="";
		while(val >= 1){
			remainder += val%8;
			val/=8;
		}
		remainder+="o0";
		return new StringBuilder(remainder).reverse().toString();
	}

}
Editor is loading...