【Java】7.0 进制转换

【二进制转十进制】

	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter a binary number");
		int num = Integer.parseInt(sc.nextLine());

		System.out.println("Your number is: " + num);
		int position = 0, sum = 0;
		while(num > 0)
		{
			if(num%10 == 1)
			{
				sum = sum + (int)(Math.pow(2,position));
				System.out.println("Sum: " + sum);
			}
			position++;
			num = num / 10;
		}
		System.out.println("Decimal number: " + sum);
	}

【二进制转十六进制】

	public static void main(String args[])
	{
		Scanner sc=new Scanner(System.in);
		System.out.println("Please enter a binary number to convert to Hex: ");
		int numBin = sc.nextInt();
		sc.close();
		int power = 0, res = 0;

		while(numBin > 0)
		{
			res = res + ((numBin%2)*(int)(Math.pow(2,power))); // extract last digit and add to red
			power++; // increase the power
			numBin = numBin / 10;  // get rid of last digit
		}
		System.out.println("Num in Decimal is: " + res);
		String digits = new String("0123456789ABCDEF");
        String number = new String("");

        int digit = 0;
        while(res > 0)
		{
			digit = res % 16;
			number = digits.charAt(digit) + number;

			res = res/16;
		}

        System.out.println(number);
	}

【十进制转十六进制】

	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter a decimal number to convert to hex: ");
		int num = Integer.parseInt(sc.nextLine());
		
		String digits = new String("0123456789ABCDEF");
		String number = new String("");
		int position = 0;
		
		while(num > 0)
		{
			position = num % 16;
			number = digits.charAt(position) + number;
			num = num / 16;
		}
		
	System.out.println("Hex: " + number);	
	}

【十进制转二进制】

	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter a number to convert to binary:");
		String number = new String("");
		int num = Integer.parseInt(sc.nextLine());

		System.out.println("Num: " + num);
		while(num > 0)
		{
			number = num%2 + number;

			num = num/2;
		}
		System.out.println("Binary number: " + number);
	}

【十进制转十六进制】

	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter a decimal number to convert to hex:");
		String number = new String(""); // string to store the hex representation
		String digits = new String("0123456789ABCDEF");
		int num = Integer.parseInt(sc.nextLine());
		int position = 0;

		System.out.println("Num: " + num);
		while(num > 0)
		{
			position = num % 16;
			number = digits.charAt(position) + number;

			num = num/16;
		}
		System.out.println("Hexadecimal number: " + number);
	}
posted @ 2021-04-13 20:57  RetenQ  阅读(76)  评论(0编辑  收藏  举报