十进制与十六进制相互转换

来源:互联网 发布:网络兼职信息网 编辑:程序博客网 时间:2024/05/20 16:44

将十进制数转换为十六进制数

package com.dx.ex;import java.util.Scanner;public class Decimal2HexConversion {public static void main(String[] args) {// Create a ScannerScanner input = new Scanner(System.in);// Prompt user to enter a decimal integerSystem.out.println("Enter a decimal integer");int decimal = input.nextInt();System.out.println("The hex number for decimal " + decimal + " is "+ decimalToHex(decimal));}/*** Convert a decimal to a hex as a string*/public static String decimalToHex(int decimal) {String hex = "";while (decimal != 0) {int hexValue = decimal % 16;hex = toHexChar(hexValue) + hex;decimal = decimal / 16;}return hex;}/*** Convert an integer to a single hex digit in a character*/public static char toHexChar(int hexValue) {if (hexValue <= 9 && hexValue >= 0) {return (char) (hexValue + '0');} else {return (char) (hexValue - 10 + 'A');}}}



十六进制数转换为十进制数

package com.dx.ex;import java.util.Scanner;public class HexToDecimalConversion {/*** @param args*/public static void main(String[] args) {// Create a ScannerScanner input = new Scanner(System.in);// Prompt user to enter a decimal integerSystem.out.println("Enter a hex number:");String hex = input.nextLine();System.out.println("The decimal value for hex number " + hex + " is "+ hexToDecimal(hex));}public static int hexToDecimal(String hex) {int decimalValue = 0;for (int i = 0; i < hex.length(); i++) {char hexChar = hex.charAt(i);decimalValue = decimalValue * 16 + hexChartoDecimal(hexChar);}return decimalValue;}public static int hexChartoDecimal(char ch) {if (ch >= 'A' && ch <= 'F') {return ch - 'A' + 10;} else {return ch - '0';}}}


原创粉丝点击